Data flow between components
Learn how to pass data between web components: properties down, events up, two-way binding without loops, a mediator for siblings, and a Proxy store.
- 01Send data down and news upPass objects to a child as properties, hear its events, and change data only where it lives, with a new copy.
- 02Bind two ways without loopsGive a component a
valueproperty in and aninputevent out, and keep it quiet when the parent sets the value. - 03Share data across the pageLet a parent pass news between siblings, or keep shared data in a small Proxy store, and know what a Proxy misses.
How do you pass data between web components?
Meena is building the order page for Leaf and Kettle. A shelf shows the teas, each on its own tile. Each tile has an Add button. Above the tiles, a line counts the cups in the order.
Asha presses Add on Oolong. The tile hears the click. But the count lives in the shelf. How does the news get up to the shelf? And how does the new number get back down to the tile?
Pass data down as properties, and send news up as events. One component owns the data. Here, that's the shelf. It gives each tile its tea as a property. A tile never changes its tea. It sends an event up, and the shelf makes the change, as a new copy, and passes it down.
Here is the whole loop. Press Add on Oolong:
<tea-shelf></tea-shelf><script type="module"> import "./tea-shelf.js"; document.querySelector("tea-shelf").teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ];</script>- Line 1 is the shelf. Line 3 loads it from the tea-shelf.js tab, and that file loads the tile.
- Lines 4 to 7 give the shelf its teas, as a property. Each tea has an id, a name, and a number of cups.
As it loads, it prints The shelf drew. Cups in all: 0, then one line for each tile. Press Add on Oolong. It prints The shelf drew. Cups in all: 1, then Oolong's tile drew. Cups: 1. Assam's tile doesn't draw at all.
add-to-cart up, and the shelf makes the change.At Leaf and Kettle, the kitchen makes every dish. Waiters carry the dishes out to the tables. When a guest wants more, the waiter doesn't cook at the table. The waiter takes the order back, and the kitchen sends out a fresh dish.
- In real life: The kitchen
- In JavaScript: The shelf, which owns the teas
- In real life: A dish carried out to a table
- In JavaScript: A tea passed down as a property
- In real life: A waiter bringing an order back
- In JavaScript: The tile's add-to-cart event
- In real life: A fresh dish from the kitchen
- In JavaScript: A new tea object, passed down again
Data down, events up, one owner. The owner passes data to its children as properties. The children report what the person did with events. Only the owner changes the data, and then it passes the new data down.
Lesson 5.4 met this rule as properties down, events up. This lesson builds it with the ReactiveTea class from lesson 18.1 and the html.js renderer from lesson 18.2. Then it goes further: two-way binding, siblings, and a shared store.
What is one-way data flow?
In one-way data flow, data moves in one direction: from its owner down to the children that show it. The owner is the one place the data lives. People call it the source of truth. Lit's docs say a component should be the source of truth for the components in its shadow root (Lit).
Here is the shelf's side, from the tea-shelf.js tab:
#add(tea) {
this.teas = this.#teas.map((each) => (each === tea ? { ...each, cups: each.cups + 1 } : each));
}
update() {
const cups = this.#teas.reduce((total, tea) => total + tea.cups, 0);
const tile = (tea) => html`<li><tea-tile .tea=${tea} @add-to-cart=${(event) => this.#add(event.tea)}></tea-tile></li>`;
render(html`<p>Cups in all: ${cups}</p><ul>${repeat(this.#teas, (tea) => tea.id, tile)}</ul>`, this.shadowRoot);
console.log(`The shelf drew. Cups in all: ${cups}`);
}- Line 2 is the only place the teas change. It makes a new array, with a new object for the tea that changed. The next section shows why.
- Line 6 adds up the cups, for the count.
- Line 7 is one tile.
.tea=${tea}is a property hole from lesson 18.2. It sets the tile'steaproperty to the tea object.@add-to-cartlistens for the tile's event, and calls#add()with its tea. - Line 8 draws the count and the tiles, keyed by id, as in lesson 18.3.
And the tile's side, from the tea-tile.js tab. First, its event:
export class AddToCartEvent extends Event {
constructor(tea) {
super("add-to-cart", { bubbles: true, composed: true });
this.tea = tea;
}
}- Line 1 makes
AddToCartEvent, a class that extendsEvent, as lesson 5.3 showed. - Line 3 names it
add-to-cart. It bubbles, andcomposedlets it leave the shelf's shadow root, as lesson 9.2 explained. - Line 4 carries the tea the tile was given.
update() {
const add = () => this.dispatchEvent(new AddToCartEvent(this.#tea));
render(html`${this.#tea.name}, cups: ${this.#tea.cups} <button @click=${add}>Add</button>`, this.shadowRoot);
console.log(`${this.#tea.name}'s tile drew. Cups: ${this.#tea.cups}`);
}- Line 2 is the Add button's listener. It dispatches the event, and does nothing else.
- Line 3 draws the name, the cups, and the button.
- Line 4 prints a line each time the tile draws, so you can see who drew.
So the tile reads its tea, and never writes to it. Why it matters: the shelf can trust its own data, because nothing else changes it.
Should an object go in an attribute or a property?
An attribute is text in the HTML. A property is a value on the element object. MDN's guide shows how the two can mirror each other (MDN), and lesson 5.1 showed what only a property can hold. Try to put a tea in an attribute:
const tile = document.createElement("tea-tile");
tile.setAttribute("tea", { name: "Oolong", cups: 0 });
console.log(tile.getAttribute("tea"));Line 2 sets the tea attribute to an object. Line 3 prints [object Object]. The object became text, and the tea is gone.
web.dev's checklist says to take rich data, like objects and arrays, only as properties (web.dev). Jake Archibald suggests attributes for settings, and properties for state (his post). Here is each way data can travel. Read each row across:
| What travels | Which way does it go? | What can it carry? | What is it for? |
|---|---|---|---|
| An attribute | Down, from the HTML or the parent. | Only text. | Settings you can write in HTML, like a tea's name. |
| A property | Down, from the parent's code. | Any value: an object, an array, a function. | Data, like the tea object a tile shows. |
| An event | Up, from the child. | Whatever its event class holds. | News, like the person pressing Add. |
| A shared store | Across, to every component that reads it. | Any object. | Data that many parts of the page show. |
Does React 19 set properties on custom elements?
Yes, when the element already has that property. React 19's release post says a prop that matches a property on the element is set as a property. Any other prop is set as an attribute (React). On the server, text and numbers become attributes, and objects are left out.
- So in React,
<tea-tile tea={oolong} />passes the object down as a property, the way.tea=${tea}does here. - Load tea-tile.js before React renders. An element that isn't defined yet has no
teaproperty, so React sets an attribute, and the object becomes[object Object]. - React's docs listen for an element's own events with
onbefore the event's name (React). Soonadd-to-carthearsadd-to-cart.
Lesson 2.5 runs all three with the real React.
Why shouldn't a child change the object it was given?
A property passes the object itself, not a copy. So the tile holds the very object the shelf holds. It could write tea.cups += 1. Why doesn't it?
Because a change inside an object runs no setter. Nothing asks for an update. Try three ways to write the shelf's #add(). In each, press Add on Oolong, then Read the data:
<tea-shelf></tea-shelf><button id="read">Read the data</button><script type="module"> import "./tea-shelf.js"; const shelf = document.querySelector("tea-shelf"); shelf.teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ]; document.querySelector("#read").addEventListener("click", () => { console.log(`Oolong's cups in the data: ${shelf.teas[0].cups}`); });</script>The data now says 1 cup, but no setter ran, so nothing asked for an update. The shelf and the tile still show 0.
- Lines 6 to 9 give the shelf its teas.
- Line 11 prints what the shelf's teas say, whatever the screen shows.
All three print Oolong's cups in the data: 1. The screens differ. Changed in place, nothing draws: the shelf and the tile still say 0. With requestUpdate(), it prints The shelf drew. Cups in all: 1, but Oolong's tile still says 0. Copied, both draw, and both say 1.
// 1. Change the tea in place
tea.cups += 1;
// 2. Change it in place, then ask for an update
tea.cups += 1;
this.requestUpdate();
// 3. Copy on write: a new array, with a new object for this tea
this.teas = this.#teas.map((each) => (each === tea ? { ...each, cups: each.cups + 1 } : each));- Line 2 changes the object in place. The shelf's
teasstill holds the same array, so no setter runs. - Lines 5 and 6 ask for an update by hand. Lit's docs warn that
requestUpdate()updates only the component that calls it (Lit). - Line 9 is copy on write. It copies the array, and makes a new object for the tea that changed. Every other tea keeps its old object.
Why did the tile miss the change in the second choice? Look at html.js's write(), from lesson 18.2:
function write(instance, values) {
values.forEach((value, hole) => {
if (Object.is(instance.values[hole], value)) return;
instance.values[hole] = value;
instance.holes[hole](value);
});
}- Line 3 skips a value that is the same as the last one written.
Object.is()calls two objects the same when they are one object, whatever is inside it. - Lines 4 and 5 write any other value. For the
.teahole, that calls the tile's setter.
The shelf passed the same object, so line 3 skipped it, and the tile's setter never ran.
A post office clerk keeps a list of the parcels already sent. The clerk only reads the label. Open a sent parcel, add a gift, and hand it in again: the label is the same, so it stays on the shelf. Pack the gift in a new parcel, and it goes out at once.
- In real life: The clerk
- In JavaScript: html.js's write()
- In real life: The parcel's label
- In JavaScript: Which object it is, for Object.is()
- In real life: Adding a gift to a parcel already sent
- In JavaScript: tea.cups += 1 on the same object
- In real life: A new parcel with a new label
- In JavaScript: A new object from copy on write
Lit's docs give the same advice: "using top-down data flow with immutable objects is best for most applications" (Lit). Immutable means never changed in place. The state management lesson shows the tools for copying: spread, map(), and filter().
Why it matters: with copy on write, each component checks one thing, whether it got a new object. Assam's tile got the same object as before, so it didn't draw at all.
How does two-way binding work in web components?
Two-way binding keeps a value the same in two places. The parent's value shows in the child. When the person changes it in the child, the parent's value changes too.
The platform has no special syntax for this. But every input already does it, in two halves:
- A value property in. The page sets
input.value. - An input event out. The input fires it when the person types.
A custom element can do the same. Here is tea-cups, a number of cups with - and + buttons, from the tea-cups.js tab:
set value(cups) {
this.#value = cups;
this.shadowRoot.querySelector("output").textContent = cups;
}
#pick(cups) {
if (cups < 1) return;
this.value = cups;
this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
}- Lines 1 to 4 are the setter. It stores the value and shows it. It fires no event.
- Line 6:
#pick()runs when the person presses - or +. Line 7 never lets it go below 1. - Line 8 sets the value through the setter. Line 9 fires
input. It bubbles and is composed, as an input's own event is when you type.
Now bind it. The page keeps cups, passes it down as .value, and takes the event back up. Press +, then Back to 1 cup. Then try the second choice, whose setter fires the event:
<p id="order"></p><button id="reset">Back to 1 cup</button><script type="module"> import { html, render } from "./html.js"; import "./tea-cups.js"; const order = document.querySelector("#order"); let cups = 1; const draw = () => render(html`<tea-cups @input=${heard} .value=${cups}></tea-cups> Cups for Asha: ${cups}`, order); function heard(event) { console.log(`Heard input: ${event.target.value}`); cups = event.target.value; draw(); } document.querySelector("#reset").addEventListener("click", () => { cups = 1; draw(); }); draw();</script>The + click fires input once. When the page passes the new value back down, and when Back to 1 cup sets it, the setter stays quiet.
- Line 8 is the binding:
@input=${heard}takes the event up, and.value=${cups}passes the value down. - Lines 9 to 13 print what they heard, store it, and draw again.
- Lines 14 to 17 set the value from the page, back to 1.
Firing for clicks prints Heard input: 2, once. Firing in the setter prints Heard input: 1 as the page loads, Heard input: 2 twice for one click, and Heard input: 1 for Back to 1 cup.
The table sums it up. Read each row across:
| When the value changes because | Fires for clicks | Fires in the setter |
|---|---|---|
| The page sets it as the page loads | No event. | An input event the page didn't need. |
| The person presses + | One input event. | Two: the click, then the echo when the page passes the value back. |
| The page puts it back to 1 | No event. | An input event, as if the person had changed it. |
The noisy one sent the page its own values back. Lit's docs say to dispatch events for the person's changes, not for changes the owner made through a property (Lit). Lesson 5.3 showed that an input stays quiet when a script sets its value.
Here, html.js stopped the echo. The second time, the value was the same, so write() skipped it. But web.dev warns that an event for a value the host set can cause an endless loop with data binding (web.dev). This listener copies the value into an order and back, as a simple binding might:
<tea-cups></tea-cups><script type="module"> import "./tea-cups.js"; const box = document.querySelector("tea-cups"); const order = { cups: 1 }; let rounds = 0; box.addEventListener("input", () => { rounds += 1; order.cups = box.value; if (rounds < 10) box.value = order.cups; }); box.value = 2; console.log(`The listener ran ${rounds} times`);</script>- Lines 7 to 11 copy the value into the order, then back into the element.
- Line 10 stops after 10 rounds, so the page can finish.
- Line 12 sets the value once, from the page.
It prints The listener ran 10 times. One value, set once, came back ten times. Without line 10's check, it goes on until Chrome stops it with RangeError: Maximum call stack size exceeded. With the quiet tea-cups, it prints The listener ran 0 times.
Two guards carry radios. Each one repeats whatever it hears, to be safe. One says gate shut. The other repeats gate shut. The first hears that, and says it again. If each guard reports only what they saw, one message is enough.
- In real life: Saying something on the radio
- In JavaScript: Firing an input event
- In real life: The other guard repeating it back
- In JavaScript: The parent writing the value back down
- In real life: Repeating what you just heard
- In JavaScript: A setter that fires for every value
- In real life: Reporting only what you saw yourself
- In JavaScript: Firing only for the person's changes
The kit's tea-quantity already works this way. Lesson 16.2 gave it a value setter that fires no event.
What did Polymer's {{ }} do?
Older tutorials show two-way binding with double curly braces. That's Polymer, an older library for web components. In a Polymer template, [[ ]] passed data one way, down. {{ }} also listened for the child's changes, and wrote them back up (Polymer).
- The child's property needed
notify: true. Then it fired an event named after the property, likevalue-changed. - For a native input, you named its event yourself:
{{hostValue::input}}.
Polymer is in maintenance mode, and its docs send new work to Lit (Polymer). Its newest release is 3.5.2. Today, two-way means what tea-cups does: a value property in, an event out. In html.js, and in Lit, you write the two halves yourself, as line 8 did.
How do sibling web components talk to each other?
Now Meena wants a badge beside the tiles, with the count. The badge and the tiles are siblings: they sit side by side in the shelf. How should the badge learn the count?
The quick way is to let the badge listen to the tiles. Try it, and then the other way. Press Add on Oolong, Add on Assam, then Empty:
<tea-shelf></tea-shelf><script type="module"> import "./tea-shelf.js"; document.querySelector("tea-shelf").teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ];</script>The badge counts add-to-cart events itself. Empty sets every tea back to 0, but no tile fires an event for that, so the badge still says 2.
- In the first choice, the badge listens for every add-to-cart on the document, and counts them itself.
- In the second, the badge has a count property, and the shelf sets it.
Both badges print The badge drew. Cups: 2 after the two adds. After Empty, the listening badge prints nothing. It still says Cups: 2, while both tiles say 0. The other badge prints The badge drew. Cups: 0.
Here is the shelf of the second choice, from its tea-shelf.js tab:
#empty() {
this.teas = this.#teas.map((tea) => ({ ...tea, cups: 0 }));
}
update() {
const cups = this.#teas.reduce((total, tea) => total + tea.cups, 0);
const tile = (tea) => html`<li><tea-tile .tea=${tea} @add-to-cart=${(event) => this.#add(event.tea)}></tea-tile></li>`;
render(
html`<p><cup-badge .count=${cups}></cup-badge> <button @click=${() => this.#empty()}>Empty</button></p>
<ul>${repeat(this.#teas, (tea) => tea.id, tile)}</ul>`,
this.shadowRoot,
);
}- Lines 1 to 3 are Empty: new objects, with no cups.
- Line 6 works out the count from the teas, the one place it lives.
- Line 9 passes the count down to the badge, as
.count. Its Empty button calls#empty().
The listening badge kept a count of its own. Two copies of the same number can drift apart, and here they did. Empty changed the teas, and no tile sent an event about it.
At a busy café, the tables don't shout across the room to each other. Each table tells the head waiter. The head waiter keeps the bookings, and tells each table what it needs to know.
- In real life: The tables
- In JavaScript: The badge and the tiles, the siblings
- In real life: Telling the head waiter
- In JavaScript: Sending an event up to the shelf
- In real life: The head waiter's bookings
- In JavaScript: The shelf's teas
- In real life: The head waiter telling a table
- In JavaScript: Passing .count down to the badge
This is the mediator pattern. Lit's docs describe it: siblings don't talk to each other. The owner handles their events, and passes the changed data back down (Lit).
What if two components are far apart on the page? Passing data through every parent between them gets tiring. Lit's docs mention another kind of mediator for that: a store that components subscribe to. That's next.
How does Proxy-based reactivity work?
A store is an object that holds shared data, outside any component. Components read from it. When it changes, every component that reads it draws again.
How does the store know it changed? A Proxy can tell. A Proxy stands in front of an object. For each read or write, it runs a function of yours, called a trap (the Proxy lesson). Here is a whole store:
const hostsOf = new WeakMap();
export function reactive(data) {
const hosts = new Set();
const store = new Proxy(data, {
set(target, key, value) {
const done = Reflect.set(target, key, value);
for (const host of hosts) host.requestUpdate();
return done;
},
});
hostsOf.set(store, hosts);
return store;
}
export function subscribe(store, host) {
const hosts = hostsOf.get(store);
hosts.add(host);
return () => hosts.delete(host);
}- Line 1 keeps each store's list of hosts out of sight. A
WeakMapholds its keys weakly, so a store nobody uses can be cleaned up. - Lines 4 and 5: reactive() makes a set of hosts, and a Proxy in front of the data.
- Line 6 is the set trap. It runs for every write through the proxy.
- Line 7 does the normal write with
Reflect.set(). Line 8 asks each host to update. - Lines 16 to 20: subscribe() adds a host, and hands back a function that removes it, as in the observer pattern.
A host is any object with requestUpdate(). Every component built on ReactiveTea has one. And since lesson 18.1, many requests before an update join one update. Here is a badge that reads the store:
connectedCallback() {
this.#stop = subscribe(order, this);
this.requestUpdate();
}
disconnectedCallback() {
this.#stop();
}
update() {
this.textContent = `Cups: ${order.cups}`;
console.log(`The ${this.id} badge drew. Cups: ${order.cups}`);
}- Line 2 subscribes when the badge joins the page. Line 3 asks for the first drawing.
- Line 7 unsubscribes when it leaves, so the store forgets it.
- Line 11 reads
order.cups. The order.js tab makes the store:reactive({ cups: 0 }).
Two badges read one store. Press Add 3 cups:
<p>Header: <cup-badge id="header"></cup-badge></p><p>Checkout: <cup-badge id="checkout"></cup-badge></p><button>Add 3 cups</button><script type="module"> import "./cup-badge.js"; import { order } from "./order.js"; document.querySelector("button").addEventListener("click", () => { order.cups += 1; order.cups += 1; order.cups += 1; });</script>- Lines 1 and 2 are two badges. Line 6 imports the same store they read.
- Lines 8 to 10 write to it three times, in one click.
As it loads, each badge draws once, with 0. Press Add 3 cups. It prints The header badge drew. Cups: 3, then The checkout badge drew. Cups: 3. Three writes, and one drawing each.
Nobody passed anything down, and nobody sent an event. Nolan Lawson starts his small framework the same way: a Proxy that notices writes, and one update in a microtask (his post).
The café's store room has a bell on its door. Whoever carries something in rings it, and the cooks come to look. But a box pushed in through the back window rings no bell.
- In real life: The store room
- In JavaScript: The data
- In real life: The bell on its door
- In JavaScript: The set trap
- In real life: The cooks who come to look
- In JavaScript: Each subscribed component's requestUpdate()
- In real life: A box pushed through the back window
- In JavaScript: A write to the data, not the proxy
What does a Proxy store miss?
A Proxy sees only the writes that go through it. Try four writes:
<script type="module"> import { reactive, subscribe } from "./store.js"; const data = { cups: 0, tea: { name: "Oolong", cups: 0 } }; const order = reactive(data); let updates = 0; subscribe(order, { requestUpdate: () => (updates += 1) }); order.cups += 1; console.log(`Cups: ${order.cups}. Oolong: ${order.tea.cups}. Updates asked for: ${updates}`); console.log(`Same object: ${order === data}`);</script>The write goes through the proxy, so the set trap stores it and asks for an update.
- Line 3 is the data. Line 4 puts the proxy in front of it.
- Line 6 subscribes a stand-in host that counts the updates it's asked for.
- Line 9 asks if the proxy and the data are the same object.
Through the proxy, it prints Updates asked for: 1. Straight to the data, 0, though the cups changed. Inside a nested object, 0. A new nested object, 1. Every choice prints Same object: false.
- The proxy is not the data. Vue's docs say the same of its own
reactive(): only the proxy is reactive (Vue). So keep only the proxy, and never write to the object behind it. - Nested objects aren't watched. Reading
order.teahands back the plain object. Vue wraps each nested object in a proxy of its own when you read it. This small store doesn't, so write a new object, as the fourth choice does.
Can a component itself be a Proxy?
No. A component keeps its private fields on the real element. Wrap the element in a Proxy, and its getters run with the proxy as this:
class TeaTile extends HTMLElement {
#tea = "Oolong";
get tea() {
return this.#tea;
}
}
customElements.define("tea-tile", TeaTile);
const tile = new Proxy(new TeaTile(), {});
console.log(tile.tea);- Line 2 is a private field. Line 5 reads it.
- Line 9 wraps a tile in a Proxy with no traps. Line 10 reads tea through it.
It throws TypeError: Cannot read private member #tea from an object whose class did not declare it. MDN calls this no private field forwarding (MDN). The DOM's own properties fail the same way: reading isConnected through the proxy throws TypeError: Illegal invocation. A Map in a store breaks for the same reason, as the Proxy lesson shows.
Why it matters: ReactiveTea itself keeps its state in private fields. So put the Proxy around plain data, and let your components stay real elements. This store also asks every subscriber to update on every write. Signals, in the next lesson, update only the components that read the value that changed.
Adding a shop to the tea kit
The kit gets a mediator in kitAfter184: tea-shop. It holds three kit components that never talk to each other: a tea-badge with the count, a tea-card for each tea, and the tea-cart from lesson 14.5.
- tea-kit/tea-shop.js (new):
tea-shop, built on ReactiveTea and drawn with html.js. - tea-kit/custom-elements.json: the new tag.
this.shadowRoot.addEventListener("tea-add", (event) => {
this.#cart().add(event.tea, event.quantity);
this.#count();
});
this.shadowRoot.addEventListener("tea-order", () => this.#count());- Line 1 listens on the shop's shadow root for a card's
tea-add, which bubbles up from the card. - Line 2 adds the tea to the cart, with the cart's
add()method. - Lines 3 and 5 count again: after an add, and after the cart's
tea-order.
#count() {
this.#cups = this.#cart().items.reduce((total, item) => total + item.quantity, 0);
this.requestUpdate();
}- Line 2 asks the cart for its items, and adds up their cups. The cart owns the order, so the count comes from the cart, not from the cards.
- Line 3 asks for an update. The shop's update() puts the count in the badge.
The cards' name and price go down as attributes. They're text, and the kit's card has taken them as attributes since lesson 6.1.
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-shop></tea-shop><script type="module"> import "./tea-kit/index.js"; const shop = document.querySelector("tea-shop"); shop.teas = [ { id: "sencha", name: "Sencha", price: 4 }, { id: "oolong", name: "Oolong", price: 5 }, ]; shop.addEventListener("tea-add", (event) => console.log(`Added ${event.quantity} ${event.tea}`)); shop.addEventListener("tea-order", () => console.log("Order placed"));</script>- Lines 6 to 9 give the shop two teas.
- Lines 10 and 11 listen on the shop. Both events come up from inside it, because they're composed.
Press Add on Sencha, then + and Add on Oolong. The badge says 3 cups, and the page prints Added 1 Sencha and Added 2 Oolong. Press Checkout, then Place order. It prints Order placed, and the badge says 0 cups.
Common mix-ups
- "Two-way binding needs a framework, like Polymer's {{ }}." No. A value property in and an input event out is two-way binding. Every input works that way.
- "A component should fire an event whenever its value changes." No. Fire it for the person's changes only. Events for values the parent set echo back, and can loop.
- "Changing an object you were given updates the page." No. It's the same object, so no setter runs, and nothing draws.
- "requestUpdate() after a change in place redraws everything." No. It redraws only the component that calls it. Its children get the same object, and skip it.
- "An event from a child always reaches the page." No. An event that isn't composed stops at the shadow root around the child (MDN).
- "Siblings should listen to each other." No. Their parent hears their events, and passes the data down. Two counts drift apart.
- "A Proxy store sees every change to its data." No. It misses writes to the object behind it, and writes inside nested objects.
- "Wrapping a component in a Proxy makes it reactive." No. Its private fields and the DOM's own properties need the real element, so reads through the proxy throw.
Practice exercises
Predict what the page prints when you press Add on Oolong, then run it.
<tea-shelf></tea-shelf><script type="module"> import "./tea-shelf.js"; document.querySelector("tea-shelf").teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ];</script><tea-shelf></tea-shelf><script type="module"> import "./tea-shelf.js"; document.querySelector("tea-shelf").teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ];</script>It prints only Oolong's tile drew. Cups: 1. The tile changed the shelf's object and drew itself, but no setter of the shelf ran, so the shelf still says Cups in all: 0.
Predict what line 13 prints, then run it.
<tea-cups></tea-cups><script type="module"> import "./tea-cups.js"; const box = document.querySelector("tea-cups"); const order = { cups: 1 }; let rounds = 0; box.addEventListener("input", () => { rounds += 1; order.cups = box.value; if (rounds < 10) box.value = order.cups; }); box.value = 2; console.log(`The listener ran ${rounds} times`);</script><tea-cups></tea-cups><script type="module"> import "./tea-cups.js"; const box = document.querySelector("tea-cups"); const order = { cups: 1 }; let rounds = 0; box.addEventListener("input", () => { rounds += 1; order.cups = box.value; if (rounds < 10) box.value = order.cups; }); box.value = 2; console.log(`The listener ran ${rounds} times`);</script>It prints The listener ran 0 times. The setter fires no event, so the listener never runs, and nothing loops.
Press Add on Oolong: the shelf says 1, but the tile still says 0. Fix the tea-shelf.js tab. What does Oolong's tile print then?
<tea-shelf></tea-shelf><button id="read">Read the data</button><script type="module"> import "./tea-shelf.js"; const shelf = document.querySelector("tea-shelf"); shelf.teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ]; document.querySelector("#read").addEventListener("click", () => { console.log(`Oolong's cups in the data: ${shelf.teas[0].cups}`); });</script><tea-shelf></tea-shelf><button id="read">Read the data</button><script type="module"> import "./tea-shelf.js"; const shelf = document.querySelector("tea-shelf"); shelf.teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ]; document.querySelector("#read").addEventListener("click", () => { console.log(`Oolong's cups in the data: ${shelf.teas[0].cups}`); });</script>Only the tea-shelf.js tab changes: #add() sets teas to a new array, with a new object for Oolong. The setter asks for the shelf's update, and Oolong's tile gets a new object, so it prints Oolong's tile drew. Cups: 1.
Press +, then Back to 1 cup. The page hears four events. Fix the tea-cups.js tab so it hears only the person's change. What does it print then?
<p id="order"></p><button id="reset">Back to 1 cup</button><script type="module"> import { html, render } from "./html.js"; import "./tea-cups.js"; const order = document.querySelector("#order"); let cups = 1; const draw = () => render(html`<tea-cups @input=${heard} .value=${cups}></tea-cups> Cups for Asha: ${cups}`, order); function heard(event) { console.log(`Heard input: ${event.target.value}`); cups = event.target.value; draw(); } document.querySelector("#reset").addEventListener("click", () => { cups = 1; draw(); }); draw();</script><p id="order"></p><button id="reset">Back to 1 cup</button><script type="module"> import { html, render } from "./html.js"; import "./tea-cups.js"; const order = document.querySelector("#order"); let cups = 1; const draw = () => render(html`<tea-cups @input=${heard} .value=${cups}></tea-cups> Cups for Asha: ${cups}`, order); function heard(event) { console.log(`Heard input: ${event.target.value}`); cups = event.target.value; draw(); } document.querySelector("#reset").addEventListener("click", () => { cups = 1; draw(); }); draw();</script>Only the tea-cups.js tab changes: the dispatch moves from the setter into #pick(). Now only the person's click fires input, so + prints Heard input: 2 once, and Back to 1 cup prints nothing.
Press Add on Oolong. The shelf counts it, but line 8 prints nothing. Fix the tea-tile.js tab. What does the page print just before the shelf draws?
<tea-shelf></tea-shelf><script type="module"> import "./tea-shelf.js"; document.querySelector("tea-shelf").teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ]; document.addEventListener("add-to-cart", (event) => console.log(`The page heard: ${event.tea.name}`));</script><tea-shelf></tea-shelf><script type="module"> import "./tea-shelf.js"; document.querySelector("tea-shelf").teas = [ { id: "oolong", name: "Oolong", cups: 0 }, { id: "assam", name: "Assam", cups: 0 }, ]; document.addEventListener("add-to-cart", (event) => console.log(`The page heard: ${event.tea.name}`));</script>Only the tea-tile.js tab changes: the event gets composed: true. Now it leaves the shelf's shadow root, and the page prints The page heard: Oolong, before the shelf draws.
Press the button: the badge stays at Oolong: 0. Fix line 7, so the store sees the change. What does the page print then?
<p>Header: <cup-badge id="header"></cup-badge></p><button>Add a cup of Oolong</button><script type="module"> import "./cup-badge.js"; import { order } from "./order.js"; document.querySelector("button").addEventListener("click", () => { order.tea.cups += 1; });</script><p>Header: <cup-badge id="header"></cup-badge></p><button>Add a cup of Oolong</button><script type="module"> import "./cup-badge.js"; import { order } from "./order.js"; document.querySelector("button").addEventListener("click", () => { order.tea = { ...order.tea, cups: order.tea.cups + 1 }; });</script>Line 7 now gives order.tea a new object. That's a write through the proxy, so the set trap asks the badge to update, and it prints The header badge drew. Oolong: 1.
Check your understanding
Question 1 of 8A shelf wants to give a tile a whole tea object, like { name: "Oolong", cups: 0 }. How should it pass it?
Choose an answer to see the explanation.
Question 2 of 8The shelf's #add() changes the tea in place and asks for an update. After Add on Oolong, what do the shelf and Oolong's tile show?
Read the code, then predictJavaScript#add(tea) { tea.cups += 1; this.requestUpdate(); }Choose an answer to see the explanation.
Question 3 of 8When should a value component like tea-cups dispatch its input event?
Choose an answer to see the explanation.
Question 4 of 8What did {{ }} mean in a Polymer template?
Choose an answer to see the explanation.
Question 5 of 8A header badge and the tea tiles sit side by side in the shelf. How should the badge learn the count?
Choose an answer to see the explanation.
Question 6 of 8This store code writes to data, not to order. How many updates does it ask for?
Read the code, then predictJavaScriptconst data = { cups: 0 }; const order = reactive(data); subscribe(order, badge); data.cups = 3;Choose an answer to see the explanation.
Question 7 of 8Why does reading tile.tea through new Proxy(tile, {}) throw, when tile.tea works?
Choose an answer to see the explanation.
Question 8 of 8React 19 renders <tea-tile tea={oolong} /> after tea-tile is defined, and the class has a tea property. What does the tile get?
Choose an answer to see the explanation.
Key takeaways
- One component owns each piece of data. It passes the data down to its children as properties.
- Children send news up as events. They never change the data they were given.
- An object goes down as a property. In an attribute, it becomes the text [object Object].
- Change data by copying it. A new object makes the setters run, and an unchanged object lets a child skip its drawing.
- Two-way binding is a value property in, and an input event out, fired only for the person's changes.
- Siblings don't talk. Their parent hears their events, and passes the data down: the mediator pattern.
- A Proxy store asks its subscribers to update on every write through it, and misses the rest.
- Keep a Proxy around plain data, never around a component.
Remember the one-liner.
Data goes down as properties, news comes up as events, and only the owner changes the data, by making a new copy.
Sources
The facts on this page come from these docs and posts:
- Component composition: passing data up and down the tree, Lit.
- Attribute reflection, MDN.
- Custom element best practices, web.dev.
- HTML attributes vs DOM properties, Jake Archibald.
- React v19: support for custom elements, React.
- Common components: custom HTML elements, React.
- Reactive properties: mutating object and array properties, Lit.
- Events: when to dispatch an event, Lit.
- Data binding: two-way bindings, Polymer.
- Feature overview, Polymer.
- Component composition: passing data across the tree, Lit.
- Event: composed property, MDN.
- Let's learn how modern JavaScript frameworks work by building one, Nolan Lawson.
- Reactivity fundamentals: reactive proxy vs. original, Vue.
- Proxy: no private field forwarding, MDN.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Signals in components. It shares state between components with signals, and updates only what depends on it.