Reactive properties
Build web component reactive properties by hand: setters that batch many changes into one update with a microtask, hasChanged, and an updateComplete promise.
- 01Write setters that schedule an updateStore the new value, ask for an update, and let one microtask draw the component once for many changes.
- 02Wait for an updateAwait an
updateCompletepromise in tests and parent components, and know the update runs before the browser paints. - 03Avoid extra rendersSkip values that didn't change, give arrays a new copy instead of pushing, and keep property changes out of the update.
What are reactive properties in a web component?
Asha is at the counter of Leaf and Kettle. Ravi's screen shows her order on a ticket: the tea, the size, and the milk. "Same again as last time," she says. That's Oolong, large, with oat milk. Ravi presses one button, and three things change at once.
How many times should the ticket draw itself? Once would do.
A reactive property is a property whose setter makes the component draw again. To keep many changes from causing many drawings, the setter only asks for an update. The component collects every change, and draws once, in a microtask: a small job the browser runs right after your code finishes.
Here is a first try. Its setters draw at once:
<tea-ticket></tea-ticket><button>Same again</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.tea = "Oolong"; ticket.size = "large"; ticket.milk = "oat"; });</script>- Line 1 is the ticket. Line 4 loads its class, from the ticket.js tab.
- Lines 7 to 9 set three properties, in one click.
- In ticket.js, each setter stores its value, then calls
#draw()at once.#draw()writes the order and prints a Drew line.
As the page loads, it prints Drew: Green tea, small, no milk. Press Same again. It prints three more lines: Drew: Oolong, small, no milk, then Drew: Oolong, large, no milk, then Drew: Oolong, large, oat milk.
One click drew the ticket three times. The first two drawings show orders nobody made. You never see them on screen, because the browser paints only after the click is handled. But the ticket did the work three times. Here it's one line of text. In a real component, it may be a whole list.
A waiter at a busy café doesn't run to the kitchen after each person orders. That would mean three trips for a table of three. The waiter writes every order on one ticket. When the whole table has finished, the waiter walks to the kitchen once.
- In real life: Each person saying what they want
- In JavaScript: Each property being set
- In real life: Writing it on the ticket
- In JavaScript: The setter storing the value
- In real life: Waiting until the whole table has ordered
- In JavaScript: Waiting for the code that's running to finish
- In real life: One walk to the kitchen
- In JavaScript: One update
Setters ask; one update draws. A setter stores the new value and asks for an update. The first ask schedules a microtask. Every ask before it runs joins the same update.
The course's components have drawn at once until now. The tabs in lesson 10.2 draw in their attribute callback. The base class in lesson 17.4 calls draw() after every change. This lesson builds a small base class, ReactiveTea, that batches instead. It uses JavaScript getters and setters and microtasks.
How does a setter schedule an update?
A setter is a method that runs when you assign to a property. ticket.tea = "Oolong" calls the tea setter, with "Oolong" as its value. Here is the new setter, from ticket.js:
set tea(value) {
const oldValue = this.#tea;
this.#tea = value;
this.requestUpdate("tea", oldValue);
}- Line 2 keeps the old value.
- Line 3 stores the new one, in a private field. A
#name can only be read inside the class. - Line 4 asks for an update. It passes the property's name and its old value. It doesn't draw.
The size and milk setters are the same, with their own names. So who draws? The ticket's class now starts with class TeaTicket extends ReactiveTea. ReactiveTea is a base class, in reactive.js. Here is its first version:
export class ReactiveTea extends HTMLElement {
#pending = false;
requestUpdate() {
if (this.#pending) return;
this.#pending = true;
queueMicrotask(() => {
this.#pending = false;
this.update();
});
}
update() {}
}- Line 2 is a flag. While it's
true, an update is already waiting. - Line 5 returns when an update is already waiting. Nothing more is needed.
- Line 6 raises the flag.
- Line 7 queues a microtask: a small job the browser runs as soon as the code running now finishes. It runs before any click, timer, or drawing on screen.
- Lines 8 and 9 run later, in that microtask. They lower the flag, then call
update(). - Line 13 is an empty
update(). The ticket replaces it with its own.
Here are the ticket's last two methods:
connectedCallback() {
this.requestUpdate();
}
update() {
const milk = this.#milk === "none" ? "no milk" : `${this.#milk} milk`;
this.textContent = `${this.#tea}, ${this.#size}, ${milk}`;
console.log(`Drew: ${this.textContent}`);
}- Lines 1 to 3: when the ticket joins the page, it asks for its first update.
- Lines 5 to 9 draw. That's the same work
#draw()did. Only the moment it runs has changed.
Ravi posts three letters one morning. With the first, he raises the little flag on the mailbox. With the second and third, he sees the flag is already up, so he just drops them in. The carrier stops once, takes all three, and lowers the flag.
- In real life: Putting a letter in the box
- In JavaScript: A setter storing its value
- In real life: Raising the flag
- In JavaScript:
this.#pending = true, and queueing the microtask - In real life: Seeing the flag already up
- In JavaScript:
if (this.#pending) return; - In real life: The carrier taking every letter, and lowering the flag
- In JavaScript: The microtask calling
update()
How do you batch updates with a microtask?
Batching means collecting many requests and doing the work once. Step 1 already batches. Try it: the page is the same, and only the files change.
<tea-ticket></tea-ticket><button>Same again</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.tea = "Oolong"; ticket.size = "large"; ticket.milk = "oat"; });</script>Each setter draws the ticket at once. Press Same again: it prints three Drew lines, and the first two show orders nobody made.
Drawing in each setter prints three Drew lines for one click. Batching prints one: Drew: Oolong, large, oat milk.
Why does one microtask catch all three sets? JavaScript runs the click handler to its end before it runs any microtask. Line 7 sets the tea, raises the flag, and queues the update. Lines 8 and 9 find the flag up, so they only store their values. Then the handler ends, and the update draws all three. MDN shows the same pattern for sending messages: the first one queues a microtask, and the rest join it.
Does a microtask run before the browser paints?
Yes. requestAnimationFrame() shows it. It asks the browser to run a function just before it draws the next frame. This page asks for one in the click handler:
<tea-ticket></tea-ticket><button>Same again</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { requestAnimationFrame(() => console.log("Next frame")); ticket.tea = "Oolong"; ticket.size = "large"; ticket.milk = "oat"; console.log("Handler done"); });</script>- Line 7 asks for a function at the next frame.
- Lines 8 to 10 set the three properties. Line 11 prints that the handler is done.
Press Same again. It prints Handler done, then Drew: Oolong, large, oat milk, then Next frame. The update ran after the handler and before the frame, every time.
That's the order of the browser's event loop: the round it repeats to run tasks, microtasks, and frames. After a task, like a click, the browser runs every microtask in the queue. Only then may it update the rendering (MDN). The HTML event loop lesson walks through those steps. Lit's docs say the same of Lit's updates: they happen "before the browser paints the next frame" (Lit).
Ravi chalks today's specials on the back of the menu board. He writes every line, then turns the board around. Customers only ever see a finished board, never one with half the teas missing.
- In real life: Writing on the back of the board
- In JavaScript: Setting properties, then the update
- In real life: Turning the board to face the shop
- In JavaScript: The browser painting
- In real life: Customers looking at the board
- In JavaScript: The person looking at the screen
Why not wait with setTimeout?
setTimeout() would batch the sets too. But a timer is a task, not a microtask. Between two tasks, the browser may paint (MDN). So the screen could show the old ticket for one more frame, after your code has already changed it. A microtask runs before that chance. Jake Archibald's Tasks, microtasks, queues and schedules explains both queues in depth.
What changed since the last update?
A component often wants to know which properties changed. Then it can skip work for the rest, the way lesson 7.3's render() skipped values that matched. Step 2 keeps a Map: a list of keys and values. Each key is a property's name. Each value is what the property held before.
requestUpdate(name, oldValue) {
if (name !== undefined && !this.#changed.has(name)) this.#changed.set(name, oldValue);
if (this.#pending) return;
this.#pending = true;
queueMicrotask(() => {
const changed = this.#changed;
this.#changed = new Map();
this.#pending = false;
this.update(changed);
});
}- Line 2 notes the name and the old value, but only if the Map doesn't have that name yet. So the Map keeps the first old value.
- Lines 6 and 7 take the Map for this update, and start an empty one for the next.
- Line 9 hands the Map to
update().
This page prints the Map. It sets the tea twice, then the size:
<loud-ticket></loud-ticket><script type="module"> import { TeaTicket } from "./ticket.js"; class LoudTicket extends TeaTicket { update(changed) { super.update(changed); for (const [name, oldValue] of changed) console.log(`${name} was ${oldValue}`); } } customElements.define("loud-ticket", LoudTicket); const ticket = document.querySelector("loud-ticket"); ticket.tea = "Oolong"; ticket.tea = "Assam"; ticket.size = "large";</script>- Lines 4 to 9 make a ticket that draws, then prints each entry of the Map.
super.update()calls the ticket's ownupdate(). - Lines 12 to 14 set the tea to Oolong, then to Assam, then the size to large.
It prints Drew: Assam, large, no milk, then tea was Green tea and size was small. One drawing, with the latest values. The Map says where each property started. Oolong never shows up: it was only a step on the way.
tea has an old value too, Oolong, but the Map already has tea, so it isn't kept.Lit hands its update methods the same Map, called changedProperties (Lit).
What is updateComplete, and why await it?
Batching has a cost. Right after you set a property, the ticket still shows the old order. Code that reads it too soon reads the wrong thing. So step 3 gives the ticket a way to say "I've drawn": a promise. A promise is an object that stands for a result that comes later. await pauses an async function until the promise has its result.
#updateComplete = Promise.resolve(true);
get updateComplete() {
return this.#updateComplete;
}
requestUpdate(name, oldValue) {
if (name !== undefined && !this.#changed.has(name)) this.#changed.set(name, oldValue);
if (this.#pending) return;
this.#pending = true;
this.#updateComplete = Promise.resolve().then(() => {
const changed = this.#changed;
this.#changed = new Map();
this.#pending = false;
this.update(changed);
return !this.#pending;
});
}- Line 1 starts with a promise that has already resolved. Awaiting it before any update doesn't wait.
- Lines 3 to 5 hand out the promise as
updateComplete. - Line 11 replaces
queueMicrotask().Promise.resolve().then()runs its function as a microtask too. Andthen()gives back a new promise, which resolves when the function returns. Line 11 keeps it. - Line 16 is the promise's result:
true, orfalsewhenupdate()asked for another update. The next section shows when.
Now read the ticket right away, and after awaiting:
<tea-ticket></tea-ticket><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); await ticket.updateComplete; ticket.tea = "Oolong"; console.log(`Right away: ${ticket.textContent}`); await ticket.updateComplete; console.log(`After await: ${ticket.textContent}`);</script>- Line 5 waits for the first drawing.
- Line 6 sets the tea. Line 7 reads the ticket at once.
- Line 8 waits for the update. Line 9 reads it again.
It prints Drew: Green tea, small, no milk and Right away: Green tea, small, no milk. Then Drew: Oolong, small, no milk and After await: Oolong, small, no milk. Right away, the ticket still showed Green tea. After the await, it showed Oolong.
At a busy café, you order and get a small buzzer. You don't stand at the counter, asking if your tea is ready. You sit down. When it buzzes, you know your tea is there.
- In real life: The buzzer you get with your order
- In JavaScript: The
updateCompletepromise - In real life: It buzzes when the tea is ready
- In JavaScript: The promise resolves after
update() - In real life: Picking up your tea after the buzz
- In JavaScript: Reading the ticket after
await
Who awaits it? Lit's docs name three cases (Lit):
- Tests. A test sets properties, awaits
updateComplete, then checks what the component shows. Exercise 6 fixes a test that forgot. - Measuring. A parent that sets a child's properties, then measures it, awaits first.
- Events. A component can await its own update before it sends an event. Then listeners see it drawn.
updateComplete promises only this element's update, not its children's. Lit's docs say the same of theirs. To be sure every component on the page has drawn, they suggest waiting for the next frame, since every microtask runs before it.
How do you avoid extra renders?
Batching stops the obvious waste. Three smaller traps are left.
Skip a value that didn't change
Setting a property to the value it already has still runs the setter. Step 3 records it, and draws again for nothing. Step 4 checks first:
hasChanged(value, oldValue) {
return !Object.is(value, oldValue);
}
requestUpdate(name, oldValue) {
if (name !== undefined) {
if (!this.hasChanged(this[name], oldValue)) return;
if (!this.#changed.has(name)) this.#changed.set(name, oldValue);
}- Lines 1 to 3 are
hasChanged().Object.is()says whether two values are the same value. - Line 7 reads the new value through the getter,
this[name]. When nothing changed, it stops. No Map entry, no update. - Line 8 is the Map line from step 2.
<tea-ticket></tea-ticket><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); await ticket.updateComplete; ticket.tea = "Green tea"; ticket.milk = "none"; requestAnimationFrame(() => console.log("Next frame"));</script>Step 3 records any set, even one that changes nothing. The ticket draws a second time, with the same words.
Without hasChanged(), it prints Drew: Green tea, small, no milk twice. The console shows a 2 beside it, because the same line came twice in a row. With hasChanged(), it prints it once. Both end with Next frame.
Why Object.is() and not !==? They differ for one value that matters here:
const cups = Number("two");
console.log(cups);
console.log(cups !== cups);
console.log(!Object.is(cups, cups));- Line 1 turns the word "two" into a number. That fails, so
cupsisNaN, "not a number". Line 2 printsNaN. - Line 3 prints
true.NaNis the one value that isn't equal to itself with!==. - Line 4 prints
false.Object.is()saysNaNis the same asNaN.
With !==, a property stuck at NaN would draw on every set. With Object.is(), it draws once. The equality lesson covers Object.is() in full. Lit's docs describe its default check as strict inequality. Its source uses Object.is(), in notEqual.
Attributes have the same trap. Lesson 3.4 showed that attributeChangedCallback() runs even when an attribute gets the value it had.
Arrays and objects changed in place
Asha wants honey. The ticket now has an extras property, an array. Its setter is like the others:
get extras() {
return this.#extras;
}
set extras(value) {
const oldValue = this.#extras;
this.#extras = value;
this.requestUpdate("extras", oldValue);
}Lines 1 to 3 hand out the array the ticket holds. Lines 5 to 9 store a new one and ask for an update. Now change it two ways:
<tea-ticket></tea-ticket><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); await ticket.updateComplete; ticket.extras.push("honey"); await ticket.updateComplete; console.log(`After push: ${ticket.textContent}`); ticket.extras = [...ticket.extras, "lemon"]; await ticket.updateComplete; console.log(`After a new array: ${ticket.textContent}`);</script>- Line 6 pushes honey into the array the ticket already holds. Line 8 prints the ticket.
- Line 9 gives the ticket a new array: a copy of the old items, then lemon. The
...spreads the old items into it. Line 11 prints it again.
It prints After push: Green tea, small, no milk. No honey, and no Drew line. Then Drew: Green tea, small, no milk, honey, lemon. The honey was in the array all along. It only showed up when something else asked for an update.
push() puts honey into the array the ticket already holds. No setter runs, and the array is the same one, so nothing asks for an update. A new array is a different object, so the setter runs and Object.is() calls it a change.Line 6 reads ticket.extras and calls push() on what it got. No setter runs, so nothing asks for an update. Even if it did, Object.is() would see the same array, and say nothing changed. Lit behaves the same way (Lit).
The kitchen works from the slips the waiter hands in. If the waiter could reach in and scribble "honey" on a slip the kitchen already has, nobody would look at it again. A new slip goes on the rail, and the cook sees it.
- In real life: The slip the kitchen already has
- In JavaScript: The array the ticket holds
- In real life: Scribbling on that slip from the dining room
- In JavaScript:
ticket.extras.push("honey") - In real life: Handing in a new slip
- In JavaScript:
ticket.extras = [...ticket.extras, "honey"] - In real life: The kitchen checking for new slips
- In JavaScript: The setter, and
hasChanged()
There are two fixes:
- Give it a new array. Make a copy with the change, as line 9 does. Copying methods like
toSorted()andwith()help (array methods that copy). - Ask by hand. Change the array, then call
ticket.requestUpdate()with no arguments. It skipshasChanged(). Lit's docs call this the advanced way: only that one component updates.
Setting a property during an update
Ravi has a rule: oat milk only comes large. Here, update() sets the size when the milk is oat:
<oat-ticket></oat-ticket><script type="module"> import { TeaTicket } from "./ticket.js"; class OatTicket extends TeaTicket { update(changed) { super.update(changed); if (this.milk === "oat") this.size = "large"; } } customElements.define("oat-ticket", OatTicket); const ticket = document.querySelector("oat-ticket"); await ticket.updateComplete; ticket.milk = "oat"; console.log(`First update: ${await ticket.updateComplete}`); console.log(`Second update: ${await ticket.updateComplete}`);</script>- Lines 4 to 9 make a ticket whose update draws, then applies the rule on line 7.
- Line 13 sets the milk to oat.
- Lines 14 and 15 print what each
updateCompletegives.
It prints Drew: Green tea, small, oat milk, then Drew: Green tea, large, oat milk. Two drawings for one change. Then First update: false and Second update: true.
Here is why. In step 4, the update lowers the flag before it calls update(). So the set on line 7 finds no update waiting, and queues a second one. The first promise resolves to false: "I asked for another." In the second update, the size is already large. hasChanged() stops the rule there.
Lit is a little different. A property set during Lit's update, up to its render(), joins that update. A set after it, in updated(), asks for another one (Lit). Lit warns about that in development mode (its source). For values worked out from other properties, Lit has willUpdate(). In our base class, set related values together, before the update. The milk setter could set the size too. Exercise 5 does that.
A value that never settles is worse. This update gives the ticket a new copy of its array every time:
<copy-ticket></copy-ticket><script type="module"> import { TeaTicket } from "./ticket.js"; class CopyTicket extends TeaTicket { updates = 0; update(changed) { super.update(changed); this.updates += 1; if (this.updates < 5) this.extras = [...this.extras]; } } customElements.define("copy-ticket", CopyTicket); const ticket = document.querySelector("copy-ticket"); requestAnimationFrame(() => console.log(`Next frame, after ${ticket.updates} updates`));</script>- Line 5 counts the updates. Line 8 adds one each time.
- Line 9 sets a new array with the same items. It looks the same, but it's a different array, so
hasChanged()says it changed. The checkthis.updates < 5stops it, only so this page can't freeze your tab. - Line 14 prints at the next frame.
It prints Drew: Green tea, small, no milk five times, which the console shows with a 5 beside it. Then Next frame, after 5 updates. All five ran before the next frame. Without the check on line 9, there would be no next frame. Each update queues another microtask, and the browser runs microtasks until the queue is empty. MDN warns about exactly this.
The table sums it up. Read each row across: what the code does, then what happens.
| What the code does | Does a setter run? | Does the ticket draw again? |
|---|---|---|
ticket.tea = "Oolong", a new value. | Yes. | Yes, once, with every other change made before the update. |
ticket.tea = "Green tea", the value it already has. | Yes. | No. hasChanged() says nothing changed. |
A number property set to NaN when it already holds NaN. | Yes. | No. Object.is(NaN, NaN) is true, even though NaN !== NaN is true too. |
ticket.extras.push("honey"). | No. Only the array changes. | No. The honey shows at the next update for some other reason. |
ticket.extras = [...ticket.extras, "honey"]. | Yes, with a new array. | Yes. |
ticket.requestUpdate(), with no arguments. | No setter is needed. | Yes. It skips hasChanged(). |
A property set inside update(). | Yes. | Yes, a second time. The first updateComplete gives false. |
How do attributes join the same update?
Pages also set attributes: <tea-ticket tea="Oolong">. Attributes are always strings, and properties can hold anything, as lesson 5.1 showed. The ticket takes both. It observes three attributes:
static observedAttributes = ["tea", "size", "milk"];When one of them changes, the browser calls attributeChangedCallback() (MDN, lesson 3.4). The ticket's callback hands the value to the property with the same name:
attributeChangedCallback(name, oldValue, newValue) {
this[name] = newValue;
}Line 2 runs the setter. So an attribute goes through the same steps as a property: hasChanged(), the Map, and the same microtask.
<tea-ticket tea="Oolong" size="large"></tea-ticket><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); await ticket.updateComplete; ticket.setAttribute("milk", "oat"); ticket.extras = ["honey"];</script>- Line 1 gives the ticket two attributes.
- Line 6 sets a third attribute. Line 7 sets a property.
It prints Drew: Oolong, large, no milk as the page loads. When ticket.js defines the tag, the browser calls the callback for each attribute, and then connectedCallback(), all in one go. So two attributes and the first ask made one drawing. Then Drew: Oolong, large, oat milk, honey: one more for lines 6 and 7.
Setting a property here never writes its attribute. That's on purpose. A setter that writes the attribute, and a callback that sets the property, call each other forever (lesson 3.4). If you want a property reflected, write the attribute in update(), and guard the callback as lesson 10.2 did. Lit reflects in its update() too.
How does Lit batch property changes?
Lit is a library for web components. Stage 8, Lit, teaches it. Its base class, ReactiveElement, does the same steps as ours. Its docs list them: the setter calls requestUpdate(), the values are compared, and an update is scheduled, once (Lit). Read each row across: the step, what our base class does, then what Lit does.
| Step | The kit's ReactiveTea | Lit's ReactiveElement |
|---|---|---|
| A property is set | Your setter stores it, then calls requestUpdate(name, oldValue). | A setter Lit writes for you does the same (lines 786 to 790). |
| Is it a change? | hasChanged(): !Object.is(value, oldValue). | The hasChanged option, by default notEqual, which is !is(value, old) (lines 403 and 404). |
| What changed | A Map keeps the first old value of each property. | The same: _$changeProperty() sets a name only if it isn't there yet (lines 1349 to 1356). |
| When it updates | Promise.resolve().then(), one microtask. | await this.__updatePromise inside an async function (line 1374), also a microtask. |
| The first update | Whenever the first property changes, connected or not. | Not until connectedCallback() calls enableUpdating() (lines 1046 to 1048 and 1141). |
| Waiting for it | updateComplete, true or false. | updateComplete, true or false (lines 1603 to 1605). |
| A set during the update | Always asks for another update. | Joins the current update until render() ends. A set in updated() asks for another, with a warning in development mode (lines 1564 to 1579). |
The line numbers are in reactive-element.ts at the lit@3.3.3 tag:
- Lines 786 to 790: the setter Lit writes for a declared property. It reads the old value, stores the new one, and calls
requestUpdate(), like our ticket's. - Lines 1281 to 1323:
requestUpdate(). It returns early whenhasChangedsays no. It schedules an update only when none is pending. - Lines 1349 to 1356: the Map keeps the first old value, as our step 2 does.
- Lines 1369 to 1390: the scheduling. Its comment says the
awaiton line 1374 "also ensures that property changes are batched". Line 1389 returns true or false, as our line 16 of step 3 does. - Lines 1036 to 1059: the constructor asks for the first update, but holds it with a promise that
connectedCallback()resolves (line 1141). So a Lit element doesn't draw until it joins a page. Ours draws whenever it's asked. - Lines 1175 to 1181:
attributeChangedCallback()sets the property, so attributes take the same path, as in our ticket. - Lines 1603 to 1605:
updateComplete.
Lit also writes the getters and setters for you, from a list of declared properties. That's why a Lit component has none of the three setters our ticket repeats.
Adding a reactive order ticket to the tea kit
The kit gets two new files in kitAfter181:
- tea-kit/reactive.js:
ReactiveTea, step 4 of this lesson, with comments. - tea-kit/tea-ticket.js:
tea-ticket, built on it. It draws its line in a shadow root, with alinepart for styling.
Here is the end of the kit's ticket:
connectedCallback() {
for (const name of ["tea", "size", "milk", "extras"]) this.#upgradeProperty(name);
this.requestUpdate();
}
attributeChangedCallback(name, oldValue, newValue) {
this[name] = newValue ?? defaults[name];
}
update(changed) {
const milk = this.#milk === "none" ? "no milk" : `${this.#milk} milk`;
this.shadowRoot.querySelector("p").textContent = [this.#tea, this.#size, milk, ...this.#extras].join(", ");
}- Line 2 keeps properties a page set before the kit loaded, with lesson 4.2's pattern. Each one goes through its setter now, so it joins the first update.
- Line 7: a removed attribute gives the property its default back, like Green tea.
- Lines 10 to 13 draw the line in the shadow root.
This page counts the writes to the ticket's line. A MutationObserver reports changes to a part of the page, in a batch:
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-ticket tea="Oolong"></tea-ticket><p><button>Same again</button></p><script type="module"> import "./tea-kit/index.js"; const ticket = document.querySelector("tea-ticket"); const line = ticket.shadowRoot.querySelector("p"); new MutationObserver((records) => console.log(`Writes: ${records.length}, ${line.textContent}`)).observe(line, { childList: true }); document.querySelector("button").addEventListener("click", async () => { ticket.size = "large"; ticket.milk = "oat"; ticket.extras = ["honey"]; await ticket.updateComplete; console.log(`Done: ${line.textContent}`); });</script>- Line 7 finds the line in the ticket's shadow root.
- Line 8 prints how many writes each batch of changes held, and what the line says.
- Lines 10 to 12 set three properties. Line 13 waits for the update, and line 14 reads the line.
As the page loads, it prints Writes: 1, Oolong, small, no milk. Press Same again: Writes: 1, Oolong, large, oat milk, honey, then Done: Oolong, large, oat milk, honey. One write for three sets.
Every other kit file stays as it was. The older components still draw at once, and pages from earlier lessons work the same. custom-elements.json documents both new modules, with update() marked protected: for subclasses only.
Why it matters: a component built on it draws once per batch of changes, and tells you when it has.
Common mix-ups
- "A setter has to draw the component." No. It can store the value and ask for an update. One update then draws every change.
- "Batching shows the change on screen later." No. The microtask runs before the next paint, so the first frame after the click already shows it.
- "setTimeout(0) batches just as well." No. A timer is a task, and the browser may paint before it runs. The old ticket could show for a frame.
- "Pushing into an array property updates the component." No. No setter runs. Give it a new array, or call
requestUpdate(). - "hasChanged() compares arrays item by item." No.
Object.is()checks whether it's the same array, not what's inside. - "You can read the component right after setting a property." No. It still shows the old values. Await
updateCompletefirst. - "updateComplete waits for child components too." No. It waits only for this element's update.
- "Setting a property inside update() is free." No. It asks for a second update. A value that never settles never stops.
Practice exercises
The page uses step 4. Predict what it prints when you press Order, then run it.
<tea-ticket></tea-ticket><button>Order</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.tea = "Assam"; ticket.size = "large"; ticket.tea = "Oolong"; });</script><tea-ticket></tea-ticket><button>Order</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.tea = "Assam"; ticket.size = "large"; ticket.tea = "Oolong"; });</script>It prints Drew: Oolong, large, no milk, once. Line 7 queues the update, and lines 8 and 9 join it. When it runs, the tea is Oolong and the size is large. Assam was never drawn.
Lines 13 and 14 set the size twice. Predict what the page prints about size.
<loud-ticket></loud-ticket><script type="module"> import { TeaTicket } from "./ticket.js"; class LoudTicket extends TeaTicket { update(changed) { super.update(changed); for (const [name, oldValue] of changed) console.log(`${name} was ${oldValue}`); } } customElements.define("loud-ticket", LoudTicket); const ticket = document.querySelector("loud-ticket"); await ticket.updateComplete; ticket.size = "large"; ticket.size = "medium"; ticket.tea = "Oolong";</script><loud-ticket></loud-ticket><script type="module"> import { TeaTicket } from "./ticket.js"; class LoudTicket extends TeaTicket { update(changed) { super.update(changed); for (const [name, oldValue] of changed) console.log(`${name} was ${oldValue}`); } } customElements.define("loud-ticket", LoudTicket); const ticket = document.querySelector("loud-ticket"); await ticket.updateComplete; ticket.size = "large"; ticket.size = "medium"; ticket.tea = "Oolong";</script>It prints size was small. Line 13 notes size with its old value, small. Line 14 finds size already in the Map, so medium's old value, large, isn't kept.
Press Add honey: nothing happens. Fix line 7. What does the page print when you press it then?
<tea-ticket></tea-ticket><button>Add honey</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.extras.push("honey"); });</script><tea-ticket></tea-ticket><button>Add honey</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.extras = [...ticket.extras, "honey"]; });</script>Line 7 now assigns a new array, so the extras setter runs, hasChanged() sees a different array, and the ticket draws: Drew: Green tea, small, no milk, honey.
Make it large does nothing. Fix the size setter in the ticket.js tab, lines 22 to 24. What does the page print then?
<tea-ticket></tea-ticket><button>Make it large</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.size = "large"; });</script><tea-ticket></tea-ticket><button>Make it large</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.size = "large"; });</script>Only the ticket.js tab changes: the size setter keeps the old value, stores the new one, and calls this.requestUpdate("size", oldValue), like the tea setter. Now Make it large prints Drew: Green tea, large, no milk.
Oat milk draws the ticket twice. Make it draw once, by changing only the ticket.js tab. What does it print then?
<tea-ticket></tea-ticket><button>Oat milk</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.milk = "oat"; });</script><tea-ticket></tea-ticket><button>Oat milk</button><script type="module"> import "./ticket.js"; const ticket = document.querySelector("tea-ticket"); document.querySelector("button").addEventListener("click", () => { ticket.milk = "oat"; });</script>Only the ticket.js tab changes: the rule moves from update() into the milk setter, line 36. Both sets now happen before the update runs, so they join it, and Oat milk prints one line: Drew: Green tea, large, oat milk.
The check prints not ok. Fix the page with one line. What does the check print then?
<tea-ticket></tea-ticket><script type="module"> import "./tea-kit/index.js"; const ticket = document.querySelector("tea-ticket"); const line = () => ticket.shadowRoot.querySelector("p").textContent; const check = (name, ok) => console.log(`${ok ? "ok" : "not ok"} - ${name}`); ticket.tea = "Oolong"; ticket.milk = "oat"; check("the ticket shows the new order", line() === "Oolong, small, oat milk");</script><tea-ticket></tea-ticket><script type="module"> import "./tea-kit/index.js"; const ticket = document.querySelector("tea-ticket"); const line = () => ticket.shadowRoot.querySelector("p").textContent; const check = (name, ok) => console.log(`${ok ? "ok" : "not ok"} - ${name}`); ticket.tea = "Oolong"; ticket.milk = "oat"; await ticket.updateComplete; check("the ticket shows the new order", line() === "Oolong, small, oat milk");</script>The new line 9 waits for the ticket's update, so the check reads the drawn line and prints ok - the ticket shows the new order. Without it, the ticket hadn't drawn even once, so the line was empty.
Check your understanding
Question 1 of 7A click handler sets tea, size, and milk on a ticket built on ReactiveTea. How many times does update() run?
Choose an answer to see the explanation.
Question 2 of 7What does this mix of a frame, a microtask, and a log print, in order?
Read the code, then predictrequestAnimationFrame(() => console.log("frame")); queueMicrotask(() => console.log("update")); console.log("set");Choose an answer to see the explanation.
Question 3 of 7What does this NaN check print?
Read the code, then predictconst price = 0 / 0; console.log(price !== price, Object.is(price, price));Choose an answer to see the explanation.
Question 4 of 7Before one update, tea is set to Oolong, then to Assam. It started as Green tea. What old value does the Map hold for tea?
Choose an answer to see the explanation.
Question 5 of 7A page runs ticket.extras.push("honey"). Why doesn't the ticket draw honey?
Choose an answer to see the explanation.
Question 6 of 7A ticket's update() sets this.size when the milk is oat. What does updateComplete give for that update?
Choose an answer to see the explanation.
Question 7 of 7Why does a test await ticket.updateComplete before reading the ticket's shadow root?
Choose an answer to see the explanation.
Key takeaways
- A reactive property's setter stores the new value, then asks for an update with its name and old value.
- The first ask raises a flag and queues one microtask. Every ask before it runs joins the same update, so many sets draw once.
- The microtask runs after your code and before the next frame, so the screen never shows a half-changed component.
- A Map hands the update each changed property, with its first old value.
updateCompleteis a promise that resolves after the update. Tests and parents await it before they read the component.hasChanged()withObject.is()skips values that didn't change, NaN included.- Changing an array in place runs no setter. Give it a new array, or call requestUpdate().
- A property set inside update() costs a second update. A value that never settles never stops.
- Attributes can set the same properties, so they join the same update.
Remember the one-liner.
Setters store and ask; one microtask draws every change, before the browser paints.
Sources
The facts on this page come from these docs, source files, and posts:
- Getters and setters, MDN.
- Using microtasks in JavaScript with queueMicrotask(): batching operations, MDN.
- Window: queueMicrotask() method, MDN.
- Tasks, microtasks, queues and schedules, Jake Archibald.
- Lifecycle: reactive update cycle, Lit.
- Lifecycle: the changedProperties map, Lit.
- Lifecycle: updateComplete, Lit.
- Reactive properties: what happens when properties change, Lit.
- Object.is(), MDN.
- Reactive properties: mutating object and array properties, Lit.
- Lifecycle: changing properties during an update, Lit.
- Using custom elements: responding to attribute changes, MDN.
- reactive-element.ts at lit@3.3.3: requestUpdate(), Lit.
- reactive-element.ts at lit@3.3.3: __enqueueUpdate(), Lit.
- reactive-element.ts at lit@3.3.3: the constructor and __initialize(), Lit.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Rendering with tagged templates. It writes markup as html`...` and updates only the values that changed.