Virtual DOM Concepts
Published by Brayan K
A virtual DOM is a lightweight in-memory copy of the real DOM that libraries like React use to compare changes (diffing) and update only the parts of the page that actually changed, making UI updates faster.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Separate a description, a DOM update and the browser’s rendering work
A virtual tree describes desired UI; it is not a live clone of every browser node or its state. Comparing descriptions can help a library decide which DOM changes to make. Whether that design is faster for a particular interaction requires measurement: creating descriptions and comparing them also takes work. These examples implement small explicit rules in plain JavaScript, not React’s internals.
const root = document.getElementById("app");
const before = { type: "p", text: "Count: 0" };
const node = document.createElement(before.type);
node.textContent = before.text;
root.append(node);
const after = { type: "p", text: "Count: 1" }; // Data describing the desired result.
console.log(node.textContent); // The existing DOM has not read that data.
if (before.text !== after.text) node.firstChild.nodeValue = after.text;
console.log(node.textContent, root.firstChild === node); // The element was preserved.
// ✅ Expected output:
// Count: 0
// Count: 1 trueThe element remains the same object while its text changes. That identity can matter for state and listeners. The browser still decides what style, layout and paint work follows. DOM Reflow, Repaint & Browser Rendering Pipeline owns those stages, and DOM Manipulation owns the node APIs.
A render calculation can produce no DOM change
const render = count => ({ type: "p", text: "Count: " + count });
const first = render(2), second = render(2);
console.log(first === second, first.type === second.type, first.text === second.text);
let writes = 0;
if (first.text !== second.text) writes++;
console.log(writes);
// ✅ Expected output:
// false true true
// 0Object identity differs, but the compared fields match. Our write counter counts only this conditional assignment decision. It is not a count of browser paints, and it does not mean the render calculation was free. React distinguishes rendering components from committing DOM changes; a component render does not automatically imply a changed DOM node.
const oldTree = { type: "p", props: { text: "A" } };
const newTree = oldTree;
newTree.props.text = "B";
console.log(oldTree.props.text, newTree.props.text);
console.log(oldTree.props.text !== newTree.props.text);
// ✅ Expected output:
// B B
// falseBoth names now refer to the changed object. If a comparison relies on the old description, preserve that earlier value. Pure Functions, Immutability & Side Effects owns changed-path copies and Deep Copy vs Shallow Copy & Data Structures owns whole-graph copy limits.
Replacing an element and updating its text preserve different things
const root = document.getElementById("app");
const paragraph = document.createElement("p");
const text = document.createTextNode("Old ");
const button = document.createElement("button"); button.textContent = "Keep";
let clicks = 0; button.addEventListener("click", () => clicks++);
paragraph.append(text, button); root.append(paragraph);
text.nodeValue = "New ";
button.click();
console.log(paragraph.textContent, paragraph.lastChild === button, clicks);
paragraph.textContent = "Replaced";
console.log(paragraph.contains(button), button.isConnected);
// ✅ Expected output:
// New Keep true 1
// false falseSetting an element’s textContent replaces its children. Updating the intended text node preserves the sibling button. A renderer must know whether a value represents text, an element or a property; treating every update as innerHTML or textContent replacement discards that distinction.
const root = document.getElementById("app");
const oldNode = document.createElement("p"); oldNode.textContent = "Label";
root.append(oldNode);
const nextNode = document.createElement("h2"); nextNode.textContent = "Label";
root.replaceChild(nextNode, oldNode);
console.log(root.firstChild.tagName, root.firstChild === oldNode, oldNode.isConnected);
// ✅ Expected output:
// H2 false falseA paragraph does not become an h2 by changing an ordinary field in our description. Replacement creates new identity. Full renderers also handle attributes, properties, events, namespaces, controlled form values and lifecycle rules; a text-and-tag demonstration does not implement those features.
Removed properties need an explicit removal path
const button = document.createElement("button");
button.setAttribute("title", "Old tip");
button.setAttribute("disabled", "");
const before = { title: "Old tip", disabled: "" };
const after = { title: "New tip" };
for (const [name, value] of Object.entries(after)) button.setAttribute(name, value);
console.log(button.title, button.disabled);
for (const name of Object.keys(before)) {
if (!Object.hasOwn(after, name)) button.removeAttribute(name);
}
console.log(button.title, button.disabled);
// ✅ Expected output:
// New tip true
// New tip falseThis narrow example owns only these two known attributes. General properties are not all string attributes: setting disabled to the string “false” still leaves that boolean attribute present. Event callbacks, styles and form value/checked state require separate contracts.
const label = document.createElement("span");
label.textContent = "<strong>user label</strong>";
console.log(label.textContent, label.children.length);
// ✅ Expected output:
// <strong>user label</strong> 0The string remains text. Arbitrary tag names, attribute names, URLs and raw HTML are separate trust decisions. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns the broader security boundary. A renderer should support a defined set of inputs rather than assuming every object can safely become HTML.
Position is a fragile identity for a reorderable list
const root = document.getElementById("app");
const row = document.createElement("div");
const label = document.createElement("span"); label.textContent = "A";
const input = document.createElement("input"); input.value = "note for A";
row.append(label, input); root.append(row);
// An index-based update reuses position zero for B.
label.textContent = "B";
console.log(label.textContent, input.value);
// ✅ Expected output:
// B note for AThe text changes to B, but the control still contains A’s note. Stable keys identify siblings across reordering. A key is not a DOM id and is not a globally unique name across the whole application. Generating a new random key on every render requests new identity instead of preserving it.
const root = document.getElementById("app");
const rows = new Map();
for (const key of ["A", "B"]) {
const row = document.createElement("div"); row.dataset.key = key;
const input = document.createElement("input"); input.value = "note for " + key;
row.append(input); root.append(row); rows.set(key, row);
}
const firstA = rows.get("A"), inputA = firstA.firstChild;
root.insertBefore(rows.get("B"), root.firstChild);
console.log([...root.children].map(row => row.dataset.key).join(","));
console.log(rows.get("A") === firstA, firstA.firstChild === inputA, inputA.value);
// ✅ Expected output:
// B,A
// true true note for AinsertBefore moves an existing node; it does not clone it. These checks establish node identity and input value preservation. They do not promise that every move preserves focus, selection, animations or embedded browsing contexts in every browser. Those require separate interaction tests or appropriate state-preserving APIs.
Removing from a live child list changes later indices
const root = document.getElementById("app");
for (const name of ["A", "B", "C"]) {
const node = document.createElement("span"); node.textContent = name; root.append(node);
}
for (let index = 1; index < root.childNodes.length; index++) {
root.removeChild(root.childNodes[index]);
}
console.log(root.textContent);
// ✅ Expected output:
// ACconst root = document.getElementById("app");
for (const name of ["A", "B", "C"]) {
const node = document.createElement("span"); node.textContent = name; root.append(node);
}
const obsolete = [...root.childNodes].slice(1);
for (const node of obsolete) node.remove();
console.log(root.textContent, root.childNodes.length);
// ✅ Expected output:
// A 1After B is removed, C moves into index one, so a forward index increment skips it. A snapshot or a carefully defined reverse traversal can fix the removal rule. Merely adding a key field to a description does not repair an algorithm that still deletes by shifting indices.
Keys identify rows; they do not guarantee minimal work
Our final renderer owns a flat list with fixed li/span/input structure. It validates a complete update before touching the DOM, reuses entries by string key and moves them into the requested order. It updates only the label text it owns; user-entered input values remain outside its state model. Removed keys lose their row, and reintroducing one later creates a new row.
The operation counters report our explicit creations, existing-row moves, removals and existing-label updates. They are not browser render counts or proof of a globally minimal edit sequence. There is no nested component tree, hydration, scheduling, React hook state or general attribute diff. React’s real reconciliation rules must be learned from React’s documentation, not inferred from this exercise.
Guided exercise: preserve a row while changing its order
Fill the literal hints. Put the existing B row before A and verify that the original B node is still used.
const root = document.getElementById("app");
const a = document.createElement("p"); a.textContent = "A";
const b = document.createElement("p"); b.textContent = "B";
root.append(a, b);
root.___(b, root.firstChild); // 👉 replace ___ with insertBefore
console.log(root.textContent);
console.log(root.firstChild === ___); // 👉 replace ___ with b
// ✅ Expected output:
// BA
// trueIndependent brief: reconcile a small keyed list
Write createKeyedList(root) for an initially empty element that this renderer exclusively owns. Return update(items). Each dense input record has a unique non-empty string key and a string label; reject malformed records and duplicates before DOM mutation. Match keys exactly without trimming. New rows contain a span label and an input with an accessible name. Labels are text, never parsed HTML.
Preserve the li and input objects for retained keys, even when moved or renamed. Do not replace user-entered input values. Remove obsolete rows and references. Return created, moved, removed and textUpdates counters; textUpdates counts changes to existing labels, not initial label creation. Check reorder, no-op, rename, deletion, reinsertion, hostile-looking label text, special key names and rejected updates leaving DOM unchanged.
function createKeyedList(root) {
if (!(root instanceof Element) || root.childNodes.length !== 0) throw new TypeError("root must be an empty element");
let entries = new Map();
return function update(items) {
if (!Array.isArray(items)) throw new TypeError("items must be an array");
const keys = new Set(), rows = [];
for (let index = 0; index < items.length; index++) {
const item = items[index];
if (item === null || typeof item !== "object" || Array.isArray(item) ||
typeof item.key !== "string" || item.key === "" || typeof item.label !== "string") {
throw new TypeError("each item needs a non-empty string key and string label");
}
if (keys.has(item.key)) throw new Error("duplicate key");
keys.add(item.key); rows.push({ key: item.key, label: item.label });
}
const next = new Map();
const counts = { created: 0, moved: 0, removed: 0, textUpdates: 0 };
let cursor = root.firstChild;
for (const row of rows) {
let entry = entries.get(row.key);
if (!entry) {
const node = document.createElement("li");
const label = document.createElement("span");
const input = document.createElement("input");
input.setAttribute("aria-label", "Note for " + row.key);
label.textContent = row.label;
node.append(label, input);
entry = { node, label, text: row.label };
counts.created++;
} else if (entry.text !== row.label) {
entry.label.textContent = row.label;
entry.text = row.label;
counts.textUpdates++;
}
if (entry.node !== cursor) {
if (entry.node.parentNode === root) counts.moved++;
root.insertBefore(entry.node, cursor);
}
cursor = entry.node.nextSibling;
next.set(row.key, entry);
}
for (const [key, entry] of entries) {
if (!next.has(key)) { entry.node.remove(); counts.removed++; }
}
entries = next;
return counts;
};
}
const root = document.createElement("ul");
document.getElementById("app").append(root);
const update = createKeyedList(root);
console.log(JSON.stringify(update([{ key: "A", label: "Alpha" }, { key: "B", label: "Beta" }])));
const originalA = root.children[0], originalB = root.children[1];
originalA.querySelector("input").value = "note for A";
console.log(JSON.stringify(update([{ key: "B", label: "Beta" }, { key: "A", label: "Alpha!" }])));
console.log(root.children[0] === originalB, root.children[1] === originalA, originalA.querySelector("input").value);
console.log(JSON.stringify(update([{ key: "B", label: "Beta" }, { key: "A", label: "Alpha!" }])));
const before = root.innerHTML;
try { update([{ key: "A", label: "changed" }, { key: "A", label: "duplicate" }]); }
catch (error) { console.log(error.name, error.message, root.innerHTML === before); }
console.log(JSON.stringify(update([{ key: "B", label: "Beta" }])));
console.log(originalA.isConnected);
update([{ key: "A", label: "<strong>plain text</strong>" }, { key: "__proto__", label: "Special" }]);
console.log(root.children[0] === originalA, root.children[0].querySelector("span").children.length);
console.log(root.children[0].querySelector("input").value === "");
console.log(JSON.stringify(update([])), root.children.length);
// ✅ Expected output:
// {"created":2,"moved":0,"removed":0,"textUpdates":0}
// {"created":0,"moved":1,"removed":0,"textUpdates":1}
// true true note for A
// {"created":0,"moved":0,"removed":0,"textUpdates":0}
// Error duplicate key true
// {"created":0,"moved":0,"removed":1,"textUpdates":0}
// false
// false 0
// true
// {"created":0,"moved":0,"removed":2,"textUpdates":0} 0Reference notes
React documents render and commit, list keys, and state preservation. This lesson executes ordinary DOM operations to make identity visible; it does not claim that every framework uses a virtual DOM or that one update strategy always wins.
Practice quiz
What does this complete program print? const description={text:"A"};const node=document.createElement("p");node.textContent=description.text;description.text="B";console.log(node.textContent);
- A
- B
- undefined
- TypeError
Answer: A. A plain object mutation does not automatically update a DOM node.
What does this complete program print? const before={text:"A"};const after=before;after.text="B";console.log(before.text!==after.text);
- true
- false
- undefined
- TypeError
Answer: false. The alleged old and new descriptions are the same changed object.
What does this complete program print? const root=document.getElementById("app");const a=document.createElement("p"),b=document.createElement("p");a.textContent="A";b.textContent="B";root.append(a,b);root.insertBefore(b,a);console.log(root.textContent,root.firstChild===b);
- AB true
- BA false
- BA true
- AB false
Answer: BA true. Moving B changes order while preserving its object identity.
What does this complete program print? const button=document.createElement("button");button.setAttribute("disabled","false");console.log(button.disabled);button.removeAttribute("disabled");console.log(button.disabled);
- false false
- true true
- false true
- true false
Answer: true false. A boolean attribute is enabled by presence, not by parsing its string as a boolean.
What does this complete program print? const node=document.createElement("span");node.textContent="<b>A</b>";console.log(node.children.length,node.textContent);
- 0 <b>A</b>
- 1 A
- 0 A
- 1 <b>A</b>
Answer: 0 <b>A</b>. textContent creates text rather than parsing markup.
What does this complete program print? const parent=document.createElement("div"),child=document.createElement("input");parent.append(child);parent.textContent="new";console.log(parent.contains(child));
- true
- false
- undefined
- TypeError
Answer: false. Assigning the parent textContent replaces its child nodes.
What does this complete program print? const keys=["A","A"];console.log(new Set(keys).size===keys.length);
- true
- undefined
- false
- TypeError
Answer: false. Duplicate sibling keys violate uniqueness.
What does this complete program print? const a={type:"p",text:"same"},b={type:"p",text:"same"};console.log(a===b,a.text===b.text);
- true true
- false false
- true false
- false true
Answer: false true. Distinct description objects can describe the same text.
Continue this course
- Previous: DOM Reflow, Repaint & Browser Rendering Pipeline
- Next: Advanced Fetch API Patterns (Retry, Timeout, AbortController) — Handle timeouts, retries, and cancellation in production-grade fetch code
- Quick reference: JavaScript cheat sheet