Lists and keys
Learn keyed list rendering in web components: render an array in one hole, keep each row with its item, move rows with moveBefore(), and handle big lists.
- 01Render a list into one holeTurn an array of templates into rows, and know that rows are reused by position unless you give keys.
- 02Keep each row with its itemKey rows with
repeat(), count what moves, what's created, and what's removed, and pick a key that really names the item. - 03Move rows without resetting themUse
moveBefore()andconnectedMoveCallback()where they exist, and choosemap(), keys,content-visibility, or windowing for big lists.
How do you render a list in a web component?
Ravi keeps Leaf and Kettle's orders on a screen. Each tea has a box for the number of cups. The list sorts itself as he types: the tea with the most cups goes to the top.
He types 2 next to Oolong. Oolong jumps to the top. But his 2 doesn't come with it. Type 2 in Oolong's box:
<ol id="menu"></ol><script type="module"> import { html, render } from "./html.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${teas.map(row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); } draw();</script>- Lines 5 to 9 are the teas. Each has a name and a number of cups.
- Lines 10 and 11 are one row: the tea's name and a box. The box's
@inputhole callsorder()as you type. No hole writes the box's value, so your number lives only in the box. - Line 12 draws the list.
teas.map(row)makes an array with one template per tea, and the whole array goes into one hole. - Lines 14 to 16 store the cups, sort the teas, and draw again. Lines 17 and 18 print where your number is.
It prints The 2 is in Green tea's box. Oolong is at the top with an empty box. Your 2 is at the bottom, next to Green tea, and so is the cursor.
Nothing crashed. The renderer put the new names into the rows it already had. It never knew which row was Oolong's. So how do you make each row stay with its tea?
Put an array of templates in a hole, and the renderer reuses rows by position: the first row gets the first item. To keep a row with its item, give each item a key, like its id. Then the renderer finds the item's own row and moves it. moveBefore() moves it without resetting its focus, animations, or custom elements.
map() keeps each row at its place and writes the new names, so the 2 stays in the third row. repeat() moves Oolong's own row to the top, box and all.Leaf and Kettle's regulars each have a mug with their name on it. Asha's already has honey stirred in. When the queue changes, a careful helper moves the named mugs into the new order. A hurried helper leaves the mugs where they stand, and pours each tea into the mug on its spot. Ravi's tea lands in Asha's mug, honey and all.
- In real life: Each mug
- In JavaScript: A row's elements
- In real life: The name on the mug
- In JavaScript: The key, like the tea's name or id
- In real life: Honey already stirred into a mug
- In JavaScript: What the template doesn't write, like typed text or focus
- In real life: Pouring each tea into the mug on its spot
- In JavaScript: Reusing rows by position
- In real life: Moving the named mugs
- In JavaScript: Moving rows by key
Rows follow their keys, not their places. Without keys, a list reuses its rows by position. With keys, each row moves with its item. Moved with moveBefore(), a row keeps its focus, its animations, and its custom elements' state.
This lesson grows the html.js renderer from lesson 18.2 so it can render lists, with a repeat() like Lit's. Lesson 7.3 first met keys, and lesson 3.5 met moveBefore(). Here, both go inside a renderer.
How does a renderer put an array into a hole?
In lesson 18.2, a hole in the content held one value, written as text. Now it can hold an array of results too. Lit does the same: its docs say a hole whose value is an array renders every item in it (Lit).
Three new functions in html.js do the work. The first is the content hole itself:
function contentHole(text) {
let rows = [];
return (value) => {
if (!Array.isArray(value) && !value?.results) {
text.data = value ?? "";
return;
}
const list = Array.isArray(value) ? byPosition(value, rows) : byKey(value, rows);
place(list, rows, text);
rows = list;
};
}- Line 1:
textis the empty text node that took the place of the hole's marker, as in lesson 18.2. It now also marks where the list ends. - Line 2:
rowsremembers the rows this hole shows, in order. - Lines 4 to 7: a value that isn't a list is written as text, as before.
- Line 8 turns the results into rows: by position for an array, and by key for
repeat(), which comes next. - Line 9 puts the rows on the page. Line 10 remembers them for the next render.
A row is one item's piece of the page: a copy of its template, with its own holes. In this html.js, each item's template must be one element, like <li>...</li>.
function newRow(result, key) {
const row = stamp(result);
write(row, result.values);
return { ...row, key, node: row.copy.firstElementChild };
}
function byPosition(results, rows) {
return results.map((result, index) => {
const row = rows[index];
if (row?.strings !== result.strings) return newRow(result);
write(row, result.values);
return row;
});
}- Lines 2 and 3 copy the template and write its values.
stamp()andwrite()are the two halves of lesson 18.2'srender(), moved into their own functions. The values go in before the row joins the page. - Line 4 keeps the row's one element as
node. - Line 9 takes the old row at the same index.
- Line 10: no row there, or a different template? Then it makes a new row.
- Lines 11 and 12 write the new values into the old row, and keep it.
lit-html does the same in _commitIterable(). It keeps one part per item, and reuses them by index (lit-html.ts, lines 1681 to 1734).
Every page from here prints what a change did with the watch.js tab:
export function watch(list) {
const observer = new MutationObserver(report);
observer.observe(list, { childList: true, subtree: true, characterData: true });
return () => report(observer.takeRecords());
}
function report(records) {
const added = new Set();
const removed = new Set();
let texts = 0;
for (const record of records) {
if (record.type === "characterData") texts += 1;
for (const node of record.addedNodes) if (node instanceof Element) added.add(node);
for (const node of record.removedNodes) if (node instanceof Element) removed.add(node);
}
const moved = [...added].filter((node) => removed.has(node)).length;
console.log(`Moved ${moved}, created ${added.size - moved}, removed ${removed.size - moved}, texts changed ${texts}`);
}- Line 2 makes a MutationObserver: an object the browser calls with a list of changes to part of the page (the observers lesson). Line 3 watches the list and everything inside it.
- Line 4 hands back a function that prints at once.
takeRecords()takes the changes waiting for the observer. - Lines 11 to 15 sort the changes into texts, added elements, and removed elements.
- Line 16: an element that was removed and added in the same batch was moved. A MutationObserver can't tell you that. MDN says even a
moveBefore()shows up as a removed node and an added node.
Now three changes to a list. Press the buttons in order:
<ul id="menu"></ul><button id="add">Add Chai</button><button id="price">Oolong costs 6</button><button id="first">Remove the first</button><script type="module"> import { html, render } from "./html.js"; import { watch } from "./watch.js"; const menu = document.querySelector("#menu"); let teas = [ { name: "Green tea", price: 4 }, { name: "Oolong", price: 5 }, { name: "Black tea", price: 3 }, ]; const item = (tea) => html`<li>${tea.name}, ${tea.price}</li>`; const draw = () => render(html`${teas.map(item)}`, menu); draw(); watch(menu); const on = (id, change) => document.getElementById(id).addEventListener("click", () => { teas = change(teas); draw(); }); on("add", (teas) => [...teas, { name: "Chai", price: 5 }]); on("price", (teas) => teas.map((tea) => (tea.name === "Oolong" ? { ...tea, price: 6 } : tea))); on("first", (teas) => teas.slice(1));</script>- Line 15 draws the teas by position. Line 17 starts watching.
- Lines 18 to 21 make
on(), a small helper. It makes a button change the array, then draw again. - Lines 22 to 24 add Chai, raise Oolong's price, and remove the first tea.
Add Chai prints Moved 0, created 1, removed 0, texts changed 0. Oolong costs 6 prints Moved 0, created 0, removed 0, texts changed 1. Remove the first prints Moved 0, created 0, removed 1, texts changed 6.
The first two are what you'd hope: one new row, then one text. The third is odd. You removed Green tea, the first row. But the renderer removed the last row. Then it rewrote the other three, because each tea moved up one place.
The café's coat rack has numbered hooks, each with a little shelf. When the first guest leaves, the attendant moves every coat one hook along and takes down the last hook. The gloves stay on their shelves. Now hook 1 has the second guest's coat, and the first guest's gloves.
- In real life: A numbered hook
- In JavaScript: A row, found by its index
- In real life: The coat on it
- In JavaScript: The item's values, written into the row
- In real life: Moving every coat one hook along
- In JavaScript: Rewriting every row after the removed item
- In real life: Gloves left on a hook's shelf
- In JavaScript: Typed text and focus, which stay in the row
Why it matters: when a row holds only what its template writes, reuse by position is fine. The page looks right. The overview's box held something no hole writes: your 2. Lit's docs warn about the same with a checkbox. Reorder the list, and the names move, but the ticks stay where they were (Lit).
Why do keys matter in a list?
A key is a value that names an item for good, like a tea's id. With keys, the renderer can ask which row showed this item last time. Lit's directive for that is repeat(items, key, template) (Lit). html.js gets its own:
export function repeat(items, key, template) {
return { keys: items.map(key), results: items.map(template) };
}Line 2 calls key() and template() on every item, and hands back both lists. It doesn't render anything. The content hole sees results, and calls byKey():
function byKey({ keys, results }, rows) {
const old = new Map(rows.map((row) => [row.key, row]));
return results.map((result, index) => {
const row = old.get(keys[index]);
if (row?.strings !== result.strings) return newRow(result, keys[index]);
write(row, result.values);
return row;
});
}- Line 2 builds a Map from each old row's key to the row. A Map finds a value by its key (Map and Set).
- Line 4 finds the row that had this item's key, wherever it was.
- Line 5: no row has this key, or the template is different? Then it makes a new row.
- Lines 6 and 7 update the old row and keep it.
Now the rows are in the new order, but the page isn't. place() fixes the page:
function place(rows, oldRows, end) {
const keep = new Set(rows);
for (const row of oldRows) if (!keep.has(row)) row.node.remove();
let next = oldRows.find((row) => keep.has(row))?.node ?? end;
for (const row of rows) {
if (row.node === next) next = next.nextSibling;
else move(row.node, next);
}
}
function move(node, next) {
next.parentNode.insertBefore(node, next);
}- Line 2 makes a Set of the new rows. Line 3 removes every old row that isn't in it.
- Line 4:
nextis the node that should come next. It starts at the first old row that stays, or at the end. - Lines 5 to 8 walk the new rows. A row already in its place just moves
nextalong, on line 6. Any other row goes in beforenext, on line 7. - Lines 11 to 13:
move()usesinsertBefore(). It moves a row that's already on the page, and inserts a new one.
Try the noon menu three ways. Oolong now costs 6 and moves up, Chai is new, and Black tea is gone:
<ul id="menu"></ul><button>Noon menu</button><script type="module"> import { html, render, repeat } from "./html.js"; import { watch } from "./watch.js"; const menu = document.querySelector("#menu"); const item = (tea) => html`<li>${tea.name}, ${tea.price}</li>`; const draw = (teas) => render(html`${teas.map(item)}`, menu); draw([ { id: "green", name: "Green tea", price: 4 }, { id: "oolong", name: "Oolong", price: 5 }, { id: "black", name: "Black tea", price: 3 }, ]); watch(menu); document.querySelector("button").addEventListener("click", () => draw([ { id: "oolong", name: "Oolong", price: 6 }, { id: "green", name: "Green tea", price: 4 }, { id: "chai", name: "Chai", price: 5 }, ]));</script>No row moves. Each row gets the tea now at its place, so six texts change: three names and three prices.
- Line 8 draws a list: with map(), or with repeat() and a key.
- Lines 9 to 13 draw the first menu. Lines 15 to 19 draw the noon menu when you press the button.
map() prints Moved 0, created 0, removed 0, texts changed 6. repeat() by index prints the same line. repeat() by id prints Moved 1, created 1, removed 1, texts changed 1.
repeat() finds each tea's old row by its key. Oolong's row moves up and gets its new price. Green tea's row stays. Chai gets a new row, and Black tea's row is removed: Moved 1, created 1, removed 1.At the theatre, you hand in your coat and get a ticket with a number. The attendant hangs coats wherever there's room. When you come back, the number finds your coat, wherever it hangs.
- In real life: The number on your ticket
- In JavaScript: The key
- In real life: The attendant's list of numbers and hooks
- In JavaScript: The Map from key to row
- In real life: Your coat, wherever it hangs
- In JavaScript: The item's own row
- In real life: A coat nobody comes back for
- In JavaScript: A row whose key is gone: removed
Why is the array index a bad key?
The index is the item's place. When the list changes order, every item gets a new index, but index 0 still names the first row. So each key finds the row at the same place. That's why repeat() by index printed exactly what map() printed. Lit's own repeat() uses the index as the key when you don't give a key function (repeat.ts, line 56). Its docs say it then works like a simple map (Lit).
A good key names the item itself, and no two items share it. Lit's docs ask for "a guaranteed unique key" for each item (Lit). Two items with one key end up sharing one row, as exercise 3 shows.
The overview's list, keyed by name
<ol id="menu"></ol><script type="module"> import { html, render, repeat } from "./html.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${repeat(teas, (tea) => tea.name, row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); } draw();</script>Lines 3 and 12 are the only changes: the import, and repeat() with the tea's name as the key. Type 2 in Oolong's box.
It prints The 2 is in Oolong's box. Oolong's own row moved to the top, with your 2 in it. But look at the cursor: it left the box. The next section explains why.
Libraries with a virtual DOM use keys the same way. Stencil compares the old and new children's keys from both ends of the list, in updateChildren() (vdom-render.ts). The build a tiny reactive UI lesson shows the same bug without keys.
Why it matters: a keyed row keeps everything the template doesn't write. That's typed text, a ticked box, and what a custom element holds.
Does moving a row with insertBefore() reset it?
Yes. insertBefore() moves an element in two steps. It takes the element out of the page, then puts it back in. Lesson 3.5 showed what taking it out resets: focus, running animations, and the page inside an iframe. A custom element in the row gets disconnectedCallback(), then connectedCallback().
Here each row also has a steeping bar, a tea-steep element. Its bar is a CSS animation that grows for 20 seconds, and it prints each callback it gets. In each version, type 2 in Oolong's box:
<ol id="menu"></ol><script type="module"> import { html, render, repeat } from "./html.js"; import "./tea-steep.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <tea-steep tea=${tea.name}></tea-steep> <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${repeat(teas, (tea) => tea.name, row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); console.log(document.activeElement.ariaLabel ? "The box kept focus" : "The box lost focus"); } draw();</script>Oolong's row moves to the top with your 2. But it left the page on the way: its element stopped and started, its bar started over, and the box lost focus.
- Line 11 gives each row a
tea-steep, with the tea's name in itsteaattribute. - Line 13 keys the rows by name.
- Line 20 asks if the box still has focus.
document.activeElementis the element with focus. A box'sariaLabelis its tea's name. The page itself has none.
With insertBefore(), it prints Stopped steeping Oolong and Started steeping Oolong, then The 2 is in Oolong's box and The box lost focus. Oolong's bar starts over from empty. With moveBefore(), it prints Moved Oolong, still steeping, the same 2 line, and The box kept focus. The bar keeps growing. lit-html prints what insertBefore() printed.
The moveBefore() choice changes only move():
function move(node, next) {
const parent = next.parentNode;
if (node.parentNode === parent && parent.moveBefore) parent.moveBefore(node, next);
else parent.insertBefore(node, next);
}- Line 3: a row already in this parent moves in one step, in a browser that has
moveBefore(). - Line 4: a new row gets
insertBefore().moveBefore()throws for a node that isn't on the page yet (lesson 3.5). Safari doesn't havemoveBefore(), so there every row takes this line.
insertBefore() takes the row out of the page and puts it back, so its element stops and starts, and the browser resets its focus and animations. moveBefore() moves it in one step, so nothing resets.tea-steep has all three callbacks. moveBefore() calls connectedMoveCallback() instead of the other two. Without that method, moveBefore() still calls disconnectedCallback(), then connectedCallback() (MDN, MDN). Exercise 6 shows it.
The table sums up the overview's list after the sort, done three ways. Read each row across:
| What the row holds | map() | repeat() with insertBefore() | repeat() with moveBefore() |
|---|---|---|---|
| Text you typed in its box | It stays at its place, next to another tea. | It moves with its tea. | It moves with its tea. |
| Focus | It stays in the same box, which now belongs to another tea. | It's lost. | It stays in the tea's box. |
| A running CSS animation | It keeps going at its place, beside another tea. | It starts over. | It keeps going. |
| A custom element | It gets no callback. Its attribute now names another tea. | It gets disconnectedCallback(), then connectedCallback(). | It gets connectedMoveCallback(). |
A trolley carries a steeping teapot and its timer. To move it across the café, one waiter unloads it, carries each thing over, and loads it again. The timer starts from zero. Another waiter just rolls the trolley. The tea keeps steeping.
- In real life: Unloading the trolley and loading it again
- In JavaScript: insertBefore(): out of the page, then back in
- In real life: Rolling the trolley across
- In JavaScript: moveBefore(): one step
- In real life: The timer starting from zero
- In JavaScript: The pair of callbacks, and a CSS animation starting over
- In real life: The tea that keeps steeping
- In JavaScript: connectedMoveCallback(), and what the browser keeps
What does Lit's repeat() use to move rows?
insertBefore(). lit-html 3.3.3's insertPart() moves a row's nodes one by one with insertBefore() (directive-helpers.ts, lines 163 to 170). That's why the lit-html choice lost focus. So a custom element should handle being moved that way. Nolan Lawson points out that a component in a list that's being sorted gets both callbacks, and shows a wait of one microtask before cleaning up (his post). The kit's tea-timer waits that way, since lesson 3.5.
When should a row be made again?
Sometimes a fresh row is the point. Say the screen switches from one customer's order to another's. The old typed note would be wrong. Lit's keyed(key, value) directive does that: when the key changes, Lit removes the old DOM before it renders the new value (Lit). In html.js, a new key does the same. The noon menu showed it: Chai got a new row, and Black tea's row was removed.
How do you render a large list?
A long list costs work in three places, and each has a fix:
- the renderer, deciding what to write and what to move;
- the browser, laying out and painting every row;
- the page, holding a node for every row.
Is repeat() always faster than map()?
No. Here are four changes to 1,000 teas, by position and by key:
<ul id="menu" hidden></ul><script type="module"> import { html, render, repeat } from "./html.js"; import { watch } from "./watch.js"; const menu = document.querySelector("#menu"); const item = (tea) => html`<li>${tea.name}</li>`; const draw = (teas) => render(html`${teas.map(item)}`, menu); let teas = Array.from({ length: 1000 }, (_, index) => ({ id: index + 1, name: `Tea ${index + 1}` })); draw(teas); const count = watch(menu); const changes = [ ["Add one at the end", (teas) => [...teas, { id: 1001, name: "Tea 1001" }]], ["Remove the first", (teas) => teas.slice(1)], ["Move the last to the top", (teas) => [teas.at(-1), ...teas.slice(0, -1)]], ["Reverse", (teas) => [...teas].reverse()], ]; for (const [label, change] of changes) { teas = change(teas); draw(teas); console.log(label); count(); }</script>Adding at the end makes one row. Every other change rewrites all 1,000 names, because every tea now sits at a new place.
- Line 8 makes 1,000 teas, each with an id and a name. Line 9 draws them.
- Lines 11 to 16 are four changes, each with a label.
- Lines 18 to 21 make each change, draw, and print what the draw did.
Here is what each printed. Read each row across:
| What changed in 1,000 teas | What map() did | What repeat() by id did |
|---|---|---|
| Add one at the end | It created 1 row. | It created 1 row. |
| Remove the first | It removed 1 row, and changed 1,000 texts. | It removed 1 row. |
| Move the last to the top | It changed 1,000 texts. | It moved 1 row. |
| Reverse | It changed 1,000 texts. | It moved 999 rows. |
Adding at the end costs the same both ways. Removing or moving one tea is far cheaper by key. Reversing is costly either way: 1,000 texts, or 999 moves.
Keys aren't free either. byKey() builds a new Map on every render. Lit's docs give two reasons to choose repeat(): moving the rows costs less than updating them, or the rows hold state that no hole controls. Otherwise, use map(), which the docs call "smaller and faster" (Lit, Lit).
Lit's repeat() is cleverer than ours. It compares the old and new keys from both ends of the list. Its comment says that handles adds, removes, swaps, and reversals in the fewest moves (repeat.ts, lines 317 to 328). Ours only walks from the front. To move the first of 1,000 teas to the end, ours moves the other 999 rows. Lit's moves 1.
Skipping rows the browser can't see
Even after the renderer is done, the browser still lays out and paints every row. One CSS rule lets it skip the rows far from view:
#menu li {
content-visibility: auto;
contain-intrinsic-size: auto 24px;
}- Line 2:
content-visibility: autolets the browser skip laying out and painting a row's contents until it comes near the view (MDN). - Line 3:
contain-intrinsic-sizegives a skipped row a height to use, so the scroll bar stays right. Withauto, the browser remembers the height the row had when it was last drawn (web.dev).
The rows stay in the DOM. MDN says skipped content stays in the accessibility tree, and find-in-page still finds it. On web.dev's demo page, rendering on load went from 232 ms to 30 ms. The web performance lesson on DOM size measures it on a long list of reviews.
What is list virtualization?
For many thousands of rows, keep most of them out of the DOM. Render only the rows near the view, and swap them as the reader scrolls. That's called windowing, or virtualization (virtualizing long lists).
A bakery has hundreds of cakes in the back, but its window shows a dozen. As people walk past, the staff swap which cakes are in the window.
- In real life: Every cake in the back
- In JavaScript: The items array
- In real life: The few cakes in the window
- In JavaScript: The rows in the DOM
- In real life: Swapping cakes as people walk past
- In JavaScript: Swapping rows as you scroll
Lit has one: @lit-labs/virtualizer. It's a Lit Labs package. Its README says it may change, or stop being supported (README).
<lit-virtualizer scroller style="height: 100px"></lit-virtualizer><script type="module"> import { html } from "https://esm.sh/lit-html@3.3.3"; import "https://cdn.jsdelivr.net/npm/@lit-labs/virtualizer@2.1.1/lit-virtualizer.js/+esm"; const list = document.querySelector("lit-virtualizer"); list.items = Array.from({ length: 10000 }, (_, index) => `Tea ${index + 1}`); list.renderItem = (tea) => html`<p style="margin: 0; height: 24px">${tea}</p>`; await list.updateComplete; await list.layoutComplete; console.log(`Teas: ${list.items.length}. Rows in the page: ${list.querySelectorAll("p").length}`);</script>- Line 1 is the virtualizer, 100 pixels tall.
scrollermakes it scroll by itself. - Lines 3 and 4 load lit-html 3.3.3 and the virtualizer 2.1.1 from CDNs. The version is in each address.
- Line 6 gives it 10,000 teas. Line 7 says how to draw one.
- Lines 8 and 9 wait for the first drawing. Line 10 prints.
It prints Teas: 10000. Rows in the page: 48. Scroll the box, and the virtualizer swaps rows in and out.
The 48 rows are the ones in view, plus up to 1,000 pixels of rows past it (BaseLayout.ts, line 149). The virtualizer renders them with Lit's repeat(). Its key is the item itself, unless you pass a keyFunction (virtualize.ts, line 45, and lines 76 to 81).
Windowing has a cost. A row that isn't in the DOM can't be found with the browser's find, and it isn't in the accessibility tree. content-visibility: auto keeps every row, so it's the gentler fix.
Adding a keyed order queue to the tea kit
The kit gets lists in kitAfter183. ReactiveTea, from lesson 18.1, calls update() once per batch, and html.js now renders lists. Together, they make a queue:
- tea-kit/html.js: this lesson's renderer, with comments, and
move()withmoveBefore(). - tea-kit/tea-queue.js (new):
tea-queue, the counter's queue of orders, each with a kittea-timer. - tea-kit/custom-elements.json:
repeat(), and the new tag.
update(changed) {
const row = (order) => html`<li part="order"><span>${order.tea}, ${order.size}</span> <tea-timer seconds=${order.seconds}></tea-timer></li>`;
render(html`<ol part="list">${repeat(this.#orders, (order) => order.id, row)}</ol>`, this.shadowRoot);
}- Line 2 is one order's row: its tea and size, and a timer with the order's seconds.
- Line 3 renders the list into the shadow root, keyed by the order's id.
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-queue></tea-queue><p><button>Rush Oolong</button></p><script type="module"> import "./tea-kit/index.js"; const queue = document.querySelector("tea-queue"); queue.orders = [ { id: 1, tea: "Assam", size: "small", seconds: 180 }, { id: 2, tea: "Green tea", size: "large", seconds: 120 }, { id: 3, tea: "Oolong", size: "large", seconds: 240 }, ]; await queue.updateComplete; const timer = queue.shadowRoot.querySelector("li:last-child tea-timer"); document.querySelector("button").addEventListener("click", async () => { const oolong = queue.orders.find((order) => order.tea === "Oolong"); queue.orders = [oolong, ...queue.orders.filter((order) => order !== oolong)]; await queue.updateComplete; const first = queue.shadowRoot.querySelector("li"); console.log(`First: ${first.querySelector("span").textContent}. Same timer: ${first.querySelector("tea-timer") === timer}`); });</script>- Lines 7 to 11 give the queue three orders. Line 13 keeps Oolong's timer.
- Lines 15 and 16 move Oolong's order to the front, in a new array.
- Line 19 prints the first row, and whether its timer is the same element.
Press Rush Oolong. It prints First: Oolong, large. Same timer: true. Oolong's own row moved up, and its timer kept counting.
The kit's timer has an empty connectedMoveCallback(), from lesson 3.3, so moveBefore() doesn't restart it. In Safari, the row moves with insertBefore(), and the timer's wait of one microtask keeps it counting. The order ticket from lesson 18.2 still renders with html.js, and reads the same.
Common mix-ups
- "The array index makes a fine key." No. The index is the place, so each key finds the row at the same place. It does exactly what
map()does. - "repeat() is always faster than map()." No. Keys cost a Map and moves. When rows hold only what the template writes, Lit's docs say to use
map(). - "A keyed list keeps everything in a moved row." No. Moved with
insertBefore(), the row loses focus, its animations start over, and its custom elements stop and start.moveBefore()keeps them. - "A MutationObserver tells you when a node moved." No. A move shows up as a removed node and an added node, even with
moveBefore(). watch.js pairs them up itself. - "Two items can share a key." No. They share one row too. Each key must name one item.
- "content-visibility: auto takes rows out of the DOM." No. They stay in the DOM and the accessibility tree. The browser only skips drawing them. Windowing is what takes rows out.
- "Lit's repeat() keeps focus in a moved row." No. lit-html 3.3.3 moves rows with
insertBefore(), so the moved row loses focus.
Practice exercises
Predict what line 14 prints, then run it.
<ul id="menu"></ul><script type="module"> import { html, render, repeat } from "./html.js"; import { watch } from "./watch.js"; const menu = document.querySelector("#menu"); const item = (tea) => html`<li>${tea.name}, ${tea.price}</li>`; const draw = (teas) => render(html`${teas.map(item)}`, menu); const green = { name: "Green tea", price: 4 }; const oolong = { name: "Oolong", price: 5 }; const black = { name: "Black tea", price: 3 }; draw([green, oolong, black]); const count = watch(menu); draw([oolong, black]); count();</script><ul id="menu"></ul><script type="module"> import { html, render, repeat } from "./html.js"; import { watch } from "./watch.js"; const menu = document.querySelector("#menu"); const item = (tea) => html`<li>${tea.name}, ${tea.price}</li>`; const draw = (teas) => render(html`${teas.map(item)}`, menu); const green = { name: "Green tea", price: 4 }; const oolong = { name: "Oolong", price: 5 }; const black = { name: "Black tea", price: 3 }; draw([green, oolong, black]); const count = watch(menu); draw([oolong, black]); count();</script>It prints Moved 0, created 0, removed 1, texts changed 4. By position, row 1 gets Oolong and row 2 gets Black tea, so their names and prices change. The last row is removed.
Only line 7 changed from exercise 1. Predict what line 14 prints now.
<ul id="menu"></ul><script type="module"> import { html, render, repeat } from "./html.js"; import { watch } from "./watch.js"; const menu = document.querySelector("#menu"); const item = (tea) => html`<li>${tea.name}, ${tea.price}</li>`; const draw = (teas) => render(html`${repeat(teas, (tea) => tea.name, item)}`, menu); const green = { name: "Green tea", price: 4 }; const oolong = { name: "Oolong", price: 5 }; const black = { name: "Black tea", price: 3 }; draw([green, oolong, black]); const count = watch(menu); draw([oolong, black]); count();</script><ul id="menu"></ul><script type="module"> import { html, render, repeat } from "./html.js"; import { watch } from "./watch.js"; const menu = document.querySelector("#menu"); const item = (tea) => html`<li>${tea.name}, ${tea.price}</li>`; const draw = (teas) => render(html`${repeat(teas, (tea) => tea.name, item)}`, menu); const green = { name: "Green tea", price: 4 }; const oolong = { name: "Oolong", price: 5 }; const black = { name: "Black tea", price: 3 }; draw([green, oolong, black]); const count = watch(menu); draw([oolong, black]); count();</script>It prints Moved 0, created 0, removed 1, texts changed 0. Each tea finds its own row, and the two that stay are already in order, so nothing moves and no text changes.
There are two orders, but after the second draw the page prints Rows: 1. Fix line 10. What does it print then?
<ul id="queue"></ul><script type="module"> import { html, render, repeat } from "./html.js"; const queue = document.querySelector("#queue"); const orders = [ { id: 1, tea: "Chai", size: "small" }, { id: 2, tea: "Chai", size: "large" }, ]; const row = (order) => html`<li>${order.tea}, ${order.size}</li>`; const draw = () => render(html`${repeat(orders, (order) => order.tea, row)}`, queue); draw(); draw(); console.log(`Rows: ${queue.children.length}`);</script><ul id="queue"></ul><script type="module"> import { html, render, repeat } from "./html.js"; const queue = document.querySelector("#queue"); const orders = [ { id: 1, tea: "Chai", size: "small" }, { id: 2, tea: "Chai", size: "large" }, ]; const row = (order) => html`<li>${order.tea}, ${order.size}</li>`; const draw = () => render(html`${repeat(orders, (order) => order.id, row)}`, queue); draw(); draw(); console.log(`Rows: ${queue.children.length}`);</script>Line 10 now keys each order by its id. The two Chai orders have two keys, so each keeps its own row, and the page prints Rows: 2.
Type 2 in Oolong's box. It prints The 2 is in Green tea's box, as map() did. Fix line 12. What does it print then?
<ol id="menu"></ol><script type="module"> import { html, render, repeat } from "./html.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${repeat(teas, (tea, index) => index, row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); } draw();</script><ol id="menu"></ol><script type="module"> import { html, render, repeat } from "./html.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${repeat(teas, (tea) => tea.name, row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); } draw();</script>Line 12 now keys each row by the tea's name, so Oolong's row moves to the top with your 2, and it prints The 2 is in Oolong's box.
Type 2 in Oolong's box: the box loses focus. Fix move() in the html.js tab, in a browser that has moveBefore(). What is the last line it prints then?
<ol id="menu"></ol><script type="module"> import { html, render, repeat } from "./html.js"; import "./tea-steep.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <tea-steep tea=${tea.name}></tea-steep> <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${repeat(teas, (tea) => tea.name, row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); console.log(document.activeElement.ariaLabel ? "The box kept focus" : "The box lost focus"); } draw();</script><ol id="menu"></ol><script type="module"> import { html, render, repeat } from "./html.js"; import "./tea-steep.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <tea-steep tea=${tea.name}></tea-steep> <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${repeat(teas, (tea) => tea.name, row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); console.log(document.activeElement.ariaLabel ? "The box kept focus" : "The box lost focus"); } draw();</script>Only the html.js tab changes: move() calls moveBefore() for a row already in the parent, and insertBefore() for a new row. Oolong's row moves in one step, so its element prints Moved Oolong, still steeping, and the last line is The box kept focus.
The row moves with moveBefore() and keeps focus, but Oolong's element still prints Stopped and Started. Fix the tea-steep.js tab. What does it print for Oolong then?
<ol id="menu"></ol><script type="module"> import { html, render, repeat } from "./html.js"; import "./tea-steep.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <tea-steep tea=${tea.name}></tea-steep> <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${repeat(teas, (tea) => tea.name, row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); console.log(document.activeElement.ariaLabel ? "The box kept focus" : "The box lost focus"); } draw();</script><ol id="menu"></ol><script type="module"> import { html, render, repeat } from "./html.js"; import "./tea-steep.js"; const menu = document.querySelector("#menu"); const teas = [ { name: "Assam", cups: 0 }, { name: "Green tea", cups: 0 }, { name: "Oolong", cups: 0 }, ]; const row = (tea) => html`<li>${tea.name} <tea-steep tea=${tea.name}></tea-steep> <input type="number" min="0" aria-label=${tea.name} @input=${(event) => order(tea, event.target.value)}></li>`; const draw = () => render(html`${repeat(teas, (tea) => tea.name, row)}`, menu); function order(tea, cups) { tea.cups = Number(cups); teas.sort((a, b) => b.cups - a.cups); draw(); const box = [...menu.querySelectorAll("input")].find((input) => input.value); if (box) console.log(`The ${box.value} is in ${box.ariaLabel}'s box`); console.log(document.activeElement.ariaLabel ? "The box kept focus" : "The box lost focus"); } draw();</script>Only the tea-steep.js tab changes: the class gets connectedMoveCallback(). moveBefore() now calls it instead of the other two, so it prints Moved Oolong, still steeping.
Check your understanding
Question 1 of 8This lesson's html.js renders a new array of results into the same hole. What does it do with the rows it already made?
Choose an answer to see the explanation.
Question 2 of 8What does this noon menu, keyed by index, print when you press Noon menu?
Read the code, then predictHTML<ul id="menu"></ul> <button>Noon menu</button> <script type="module"> import { html, render, repeat } from "./html.js"; import { watch } from "./watch.js"; const menu = document.querySelector("#menu"); const item = (tea) => html`<li>${tea.name}, ${tea.price}</li>`; const draw = (teas) => render(html`${repeat(teas, (tea, index) => index, item)}`, menu); draw([ { id: "green", name: "Green tea", price: 4 }, { id: "oolong", name: "Oolong", price: 5 }, { id: "black", name: "Black tea", price: 3 }, ]); watch(menu); document.querySelector("button").addEventListener("click", () => draw([ { id: "oolong", name: "Oolong", price: 6 }, { id: "green", name: "Green tea", price: 4 }, { id: "chai", name: "Chai", price: 5 }, ])); </script>Choose an answer to see the explanation.
Question 3 of 8Why is a key needed to keep a row with its item?
Choose an answer to see the explanation.
Question 4 of 8A keyed list moves a row with insertBefore(). The row has a box with focus in it. What happens to the focus?
Choose an answer to see the explanation.
Question 5 of 8A row moved with moveBefore() holds a custom element that has connectedMoveCallback(). Which of its callbacks run?
Choose an answer to see the explanation.
Question 6 of 8Two orders of Chai are keyed by the tea's name. What goes wrong when the list renders again?
Choose an answer to see the explanation.
Question 7 of 8When is map() the better choice for a list?
Choose an answer to see the explanation.
Question 8 of 8What does content-visibility: auto do for a row far from view?
Choose an answer to see the explanation.
Key takeaways
- An array of templates in one hole renders one row per item. Without keys, rows are reused by position.
- Reuse by position rewrites the rows. Typed text, focus, and anything else no hole writes stays at its place.
- A key names an item for good. A Map from key to row finds the item's own row, wherever it moved.
- The index is not a key: it names a place. And no two items may share a key.
insertBefore()moves a row by taking it out, so focus is lost, animations restart, and custom elements stop and start.moveBefore()moves a row in one step, and callsconnectedMoveCallback(). Safari doesn't have it, so keepinsertBefore()as the fallback.- Use
map()when rows hold no state of their own. Use keys when they do, or when moving is cheaper than rewriting. - For big lists,
content-visibility: autoskips drawing far rows. Windowing keeps them out of the DOM.
Remember the one-liner.
Key each row by its item, so it moves with the item, and move it with moveBefore() so it keeps its state.
Sources
The facts on this page come from these docs, source files, and posts:
- Lists: rendering arrays, and the repeat directive, Lit.
- lit-html.ts at lit@3.3.3: ChildPart._commitIterable(), Lit.
- Lists: when to use map or repeat, Lit.
- Built-in directives: repeat, Lit.
- Built-in directives: keyed, Lit.
- repeat.ts at lit@3.3.3: the index as the default key, Lit.
- repeat.ts at lit@3.3.3: the keyed update, Lit.
- vdom-render.ts at v4.45.2: updateChildren(), Stencil.
- Element: moveBefore(), moving custom elements while preserving state, MDN.
- Using custom elements: lifecycle callbacks and state-preserving moves, MDN.
- directive-helpers.ts at lit@3.3.3: insertPart(), Lit.
- Avoiding unnecessary cleanup work in disconnectedCallback, Nolan Lawson.
- content-visibility, MDN.
- content-visibility: the new CSS property that boosts your rendering performance, web.dev.
- @lit-labs/virtualizer 2.1.1: README, Lit.
- virtualize.ts at @lit-labs/virtualizer@2.1.1: the rows in view, through repeat(), Lit.
- BaseLayout.ts at @lit-labs/virtualizer@2.1.1: the overhang, Lit.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Data flow between components. It passes data down, sends changes up, and decides when two-way binding is worth it.