The previous lesson in this module covered reading and validating form data, and this one builds on that work by showing how to update a list of results without throwing the whole list away. Every list interface eventually has to change, because a filter narrows the results, a row is deleted, or a server sends fresher data. The tempting shortcut is to rebuild the list from a string every single time. It works right up until somebody is halfway through typing in a row, and then it destroys exactly what they were doing.
What goes wrong when you rewrite a list from scratch every time?
The simple version is short and easy to read. You have an array of data, you turn it into a string of list items, and you give that string to innerHTML. Three lines of code, and it always produces the correct output.
<label for="filter">Filter</label>
<input id="filter" type="search" placeholder="Filter results">
<ul id="results"></ul>
<p id="status"></p>
const list = document.querySelector("#results");
const catalogue = [
{ id: "a", label: "Alpha", count: 3 },
{ id: "b", label: "Beta", count: 5 },
];
function renderNaive(items) {
let html = "";
for (const item of items) {
html = html + '<li class="result" data-id="' + item.id + '">'
+ '<span class="label">' + item.label + '</span>'
+ '<input class="qty" type="number" value="' + item.count + '"></li>';
}
list.innerHTML = html;
}
renderNaive(catalogue);
// Somebody starts typing in the first quantity box.
const qty = list.querySelector(".qty");
qty.focus();
qty.value = "9";
// A second render replaces every element, so the typed value is gone.
renderNaive(catalogue);
console.log(list.querySelector(".qty").value); // "3"
console.log(document.activeElement === document.body); // true, focus was lost
Nothing about that code is wrong at the level of the output. The rendered HTML is identical before and after the second render. But the second render threw away the original elements and built new ones, and the browser took the focus, the text cursor, and the uncommitted value down with them. Everything that was typed into that input now lives in a variable that no longer exists.
Exactly what does a full re-render throw away?
It is worth being specific about this, because the list is longer than most people expect. The focus and the text selection inside a field are lost. Anything that was typed but not yet submitted is lost. The scroll position inside a scrollable region is lost. CSS transitions and animations restart, because they are attached to the old elements. Any event listener that was attached to a child element rather than to the container is lost. Media that was playing stops. And the scrollTop of every scrollable descendant is reset.
The general rule is that the page holds state that your JavaScript does not know about. A full re-render is a promise that the page holds nothing worth keeping, and the moment a person can type into it, that promise breaks.
How do you update only the parts that changed?
The fix is to keep the elements that you already have and to change only what the data owns. That means holding on to each row after you create it, so that you can find it again the next time. A Map that goes from a stable id to the element is the simplest way to do that.
Each update then does three things. It removes the rows whose ids are no longer in the data, it creates the rows that are missing, and it edits the text of the rows that are already on the screen. Nothing else is touched, so the focus, the selection, and any half-typed values all survive.
const list = document.querySelector("#results");
const rows = new Map();
function update(next) {
// Remove the rows that are no longer in the data.
const wanted = new Set();
for (const item of next) {
wanted.add(item.id);
}
for (const entry of rows) {
const id = entry[0];
const row = entry[1];
if (!wanted.has(id)) {
row.remove();
rows.delete(id);
}
}
for (const item of next) {
let row = rows.get(item.id);
if (!row) {
row = document.createElement("li");
row.className = "result";
row.dataset.id = item.id;
row.innerHTML = '<span class="label"></span><input class="qty" type="number">';
rows.set(item.id, row);
list.append(row);
}
row.querySelector(".label").textContent = item.label;
}
}
update([{ id: "a", label: "Alpha" }]);
const qty = list.querySelector(".qty");
qty.focus();
qty.value = "9";
update([{ id: "a", label: "Alpha (updated)" }]);
console.log(list.querySelector(".label").textContent); // "Alpha (updated)"
console.log(list.querySelector(".qty").value); // "9", the typed value survived
console.log(document.activeElement === qty); // true, focus stayed put
Notice the last line of the update function. It writes to .label and to nothing else. The quantity input belongs to the person and not to your data, so your update function must leave it alone. Ownership of a field is the rule that makes incremental updates safe, because if you write to a field that you do not own, you will overwrite something that a person typed.
There is a second small choice in that function. The label is written with textContent rather than with innerHTML, so a label that contains angle brackets is shown as characters instead of being parsed as markup. It is the same rule that applies anywhere text reaches the page, and it costs nothing to follow here.
Why does keying by id beat keying by array index?
When you match incoming data to the elements that are already on the page, you need a key. There are two candidates, and they are the array index and a stable id. Index keying assumes that an item never changes position. That assumption holds until the list is sorted, filtered, or reordered, and then the element that a person is interacting with quietly starts showing different data.
const list = document.querySelector("#results");
const rows = []; // one element per array position
function renderByIndex(data) {
data.forEach(function (item, index) {
let row = rows[index];
if (!row) {
row = document.createElement("li");
row.className = "result";
rows[index] = row;
}
row.textContent = item.label;
if (!row.isConnected) {
list.append(row);
}
});
}
renderByIndex([{ id: "a", label: "Alpha" }, { id: "b", label: "Beta" }]);
const alphaRow = rows[0];
renderByIndex([{ id: "b", label: "Beta" }, { id: "a", label: "Alpha" }]);
console.log(alphaRow.textContent); // "Beta", the element that showed Alpha now shows Beta
The element that was showing Alpha is now showing Beta, because index zero no longer means Alpha. If that element had a focused input inside it, the person would watch their own row change underneath them. Keying by a stable id means that the element follows the item, so reordering the data reorders the page and nothing else changes.
When should you move an existing node rather than build a new one?
Sorting and reordering are the cases where you should move nodes rather than recreate them. Calling append on a node that is already in the document moves it, so reordering a list is a handful of append calls and no new elements at all. Every row keeps its listeners, its scroll position, and anything that a person typed into it.
const list = document.querySelector("#results");
const alpha = document.createElement("li");
const beta = document.createElement("li");
alpha.className = "result";
beta.className = "result";
alpha.textContent = "Alpha";
beta.textContent = "Beta";
list.append(alpha, beta);
console.log([...list.children].map((row) => row.textContent)); // ["Alpha","Beta"]
// Moving an existing node keeps its state, its listeners, and its focus.
list.append(alpha);
console.log([...list.children].map((row) => row.textContent)); // ["Beta","Alpha"]
How do you apply many updates without rendering dozens of times?
Incremental updates still cost something, and if your data changes twenty times in one second, then twenty separate edits to the page show up as a flicker. The fix is to join them together. Mark that an update is needed, and then do the actual work once, on the next frame.
requestAnimationFrame is the right clock for this. It runs just before the browser paints, so the person sees one combined result instead of twenty partial ones. The queued flag is what stops three calls in the same tick from scheduling three separate frames.
let queued = false;
let paints = 0;
function scheduleUpdate(paint) {
if (queued) {
return;
}
queued = true;
requestAnimationFrame(function () {
queued = false;
paint();
});
}
function paint() {
paints = paints + 1;
console.log("painted", paints);
}
scheduleUpdate(paint);
scheduleUpdate(paint);
scheduleUpdate(paint);
console.log("three updates requested");
The output shows three updates requested and a single paint. The flag is reset inside the frame callback and not before it, so any update that arrives while a frame is already waiting is simply absorbed into the one that is scheduled.
The same trick works for any kind of pending work. A common companion to it is to keep a single flag that says the data has changed, and to read that flag inside the frame callback. That way the update always renders the newest data and not the data that happened to trigger the very first request.
The incremental update reference
rows.set(id, element)keeps a handle on each row so that it can be reused later.row.remove()together withrows.delete(id)drops the rows that left the data.row.querySelector(".label").textContent = valueedits only the fields that your data owns.row.dataset.idgives you a stable key that survives reordering, unlike an array index.list.append(existingNode)moves a node to reorder the list without recreating it.requestAnimationFrametogether with aqueuedflag joins a burst of updates into one paint.
Try it yourself: build a list of five rows, each with a text input, and add a button that puts a new row at the top. Give the button a handler that rebuilds the whole list with innerHTML, then type into one of the inputs and press the button, and watch the text disappear. Now change the handler so that it creates a single new element and calls list.prepend instead, and confirm that the typed text and the focus both survive. Finally, add a delete button to each row that removes only that one row and leaves the others untouched.