Full answer
Real DOM updates are not free, and rewriting innerHTML throws away state such as focus and scroll position. A virtual DOM keeps a light description of the UI as plain objects, such as { type: 'li', props: { class: 'a' }, children: [...] }. Rendering becomes a pure function of state to a tree, and the library finds the smallest set of real changes.
The minimal algorithm compares nodes pair by pair at the same position:
- No old node: create the new element and append it.
- No new node: remove the old element.
- Different type (or one is text and the other an element, or the texts differ): replace the whole node.
- Same element type: update the attributes (set changed ones, remove missing ones), then diff the children by index, up to the longer of the two lists.
This is a linear walk, not the general tree edit distance, which would be far too slow. It relies on two assumptions, which React also makes: elements of different types produce different trees, and a developer can give list items a stable key.
The limitation of index matching is lists. If you insert an item at the start, every following item looks changed, and inputs can keep the wrong state. With keys, the algorithm builds a map from key to old node, reuses the node for the same key, and moves it instead of rebuilding it. The mini version below does not implement keys, and says so.
Real libraries add much more: event handler props, batching updates, scheduling, components with state, and fine-grained alternatives like Svelte and Solid that skip the virtual tree and update exact nodes. A virtual DOM is not always faster than direct DOM updates, but it makes updates predictable and avoids a lot of manual code.
const h = (type, props, ...children) => ({ type, props: props || {}, children: children.flat() });
const log = [];
function create(vnode) {
if (typeof vnode === 'string') return document.createTextNode(vnode);
const el = document.createElement(vnode.type);
for (const [name, value] of Object.entries(vnode.props)) el.setAttribute(name, value);
vnode.children.forEach((child) => el.appendChild(create(child)));
return el;
}
const changed = (a, b) => typeof a !== typeof b || (typeof a === 'string' && a !== b) || a.type !== b.type;
function patchProps(el, oldProps, newProps) {
for (const name of Object.keys({ ...oldProps, ...newProps })) {
if (!(name in newProps)) {
el.removeAttribute(name);
log.push(`remove attr ${name}`);
} else if (oldProps[name] !== newProps[name]) {
el.setAttribute(name, newProps[name]);
log.push(`set attr ${name}=${newProps[name]}`);
}
}
}
function update(parent, newNode, oldNode, index = 0) {
const el = parent.childNodes[index];
if (oldNode === undefined) {
parent.appendChild(create(newNode));
log.push('create ' + (newNode.type || 'text'));
} else if (newNode === undefined) {
parent.removeChild(el);
log.push('remove ' + (oldNode.type || 'text'));
} else if (changed(newNode, oldNode)) {
parent.replaceChild(create(newNode), el);
log.push('replace ' + (oldNode.type || 'text') + ' with ' + (newNode.type || 'text'));
} else if (typeof newNode !== 'string') {
patchProps(el, oldNode.props, newNode.props);
const length = Math.max(newNode.children.length, oldNode.children.length);
// walk children from the end so removals do not shift the indexes still to visit
for (let i = length - 1; i >= 0; i--) update(el, newNode.children[i], oldNode.children[i], i);
}
}
const view = (state) =>
h('div', { id: 'app', class: state.dark ? 'dark' : 'light' },
h('h1', null, 'Todos: ' + state.items.length),
h('ul', null, state.items.map((text) => h('li', null, text))),
state.error ? h('p', { role: 'alert' }, state.error) : h('span', null, 'ok'));
const root = document.body;
let current = view({ dark: false, items: ['milk', 'eggs'], error: '' });
root.appendChild(create(current));
console.log(root.innerHTML);
const next = view({ dark: true, items: ['milk', 'eggs', 'tea'], error: 'offline' });
const ulBefore = root.querySelector('ul');
update(root, next, current);
current = next;
console.log(log.join('\n'));
console.log(root.innerHTML);
console.log('same ul element reused:', root.querySelector('ul') === ulBefore);
log.length = 0;
const shorter = view({ dark: true, items: ['eggs'], error: 'offline' });
update(root, shorter, current);
console.log(log.join('\n'));
console.log(root.innerHTML);Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: <div id="app" class="light"><h1>Todos: 2</h1><ul><li>milk</li><li>eggs</li></ul><span>ok</span></div> set attr class=dark replace span with p create li replace text with text <div id="app" class="dark"><h1>Todos: 3</h1><ul><li>milk</li><li>eggs</li><li>tea</li></ul><p role="alert">offline</p></div> same ul element reused: true remove li remove li replace text with text replace text with text <div id="app" class="dark"><h1>Todos: 1</h1><ul><li>eggs</li></ul><p role="alert">offline</p></div>
Key points
- A virtual DOM is a plain object tree; rendering is a function from state to that tree.
- The diff compares old and new nodes by position: create, remove, replace on type change, update props, recurse into children.
- Linear time works because it assumes different types give different trees.
- Index matching breaks for reordered lists; keys fix that by reusing nodes with the same key.
- Fine-grained frameworks update exact nodes without a virtual tree.
Common mistakes
- Replacing the whole tree with innerHTML and losing focus, scroll position, and input state.
- Matching list items by index without keys when the list can reorder.
- Comparing children without handling lists of different length.
- Using array index as the key for lists that reorder.
Follow-ups
- How do keys change the algorithm for lists?
- Why is a virtual DOM not always faster than updating the DOM directly?
- How do Svelte or Solid avoid a virtual DOM?
Tips
- Describe the four cases (create, remove, replace, update) first.
- Say that linear diffing depends on the types and keys assumptions.
- Name the list problem and how keys solve it.