The virtual DOM and diffing

Compare two trees and touch only what changed.

Builds on Rendering elements.

At the end of chapter 4, the toy and React ran the same components with the same "render everything again" calls, and behaved completely differently. The toy rebuilt five DOM elements per keystroke and lost the input's focus. React created nothing after the first render and let you type.

The difference is memory. React keeps the element tree from the last render, compares it with the new one, and applies only the differences to the DOM. That comparison is called diffing, and the process around it is reconciliation. In this chapter the toy learns to do it, and you'll see the two rules that make it fast enough to run on every update. Then we'll deal honestly with the most repeated claim about it: that the virtual DOM is "faster than the DOM".

The problem: comparing two trees is expensive#

You have two trees of elements, the previous render and this one. You want the cheapest list of DOM operations (create, remove, move, update) that turns the old DOM into the new one.

Solved in general, that's the tree edit distance problem, and the best general algorithms take on the order of O(n³) time for n nodes. React's original docs put it plainly: a 1,000 element screen would need on the order of a billion comparisons. On every keystroke. Not an option.

So React doesn't solve the general problem. It solves a narrower one in O(n), a single walk down both trees at once, by assuming two things that are almost always true of UIs:

  1. Two elements of different types produce different trees. If a <div> became a <section>, or <Profile> became <Settings>, React doesn't look inside for similarities. It tears down the old subtree and builds the new one.
  2. Keys tell you which children are the same across renders. Among siblings, a stable key lets React match an item even if it moved. Without keys, children are matched by position.

The original docs call these assumptions valid for almost all practical use cases. When they hold, the result is close to what the expensive algorithm would find. When they don't, React does more DOM work than strictly necessary (and can throw away state you wanted kept), but the screen it produces is still correct. This chapter builds rule 1 and position matching; chapter 6 adds keys.

Build it: a reconciler#

Stage 5 of the toy keeps, for each container, the tree it rendered last time. Not just the elements: it also needs to know which DOM node each element produced. So it stores an instance per element:

// host element: { element, dom, childInstances }
// component:    { element, dom, childInstance }   (dom is its child's node)

render now looks up the previous instance for the container and hands everything to reconcile(parentDom, instance, element), which returns the new instance:

export function render(element, container) {
  const previous = container.__instance ?? null; // what we rendered last time
  container.__instance = reconcile(container, previous, element);
}

reconcile is the whole algorithm. It compares one old instance with one new element and handles five cases:

export function reconcile(parentDom, instance, element) {
  if (instance == null) {
    // Nothing was here: create.
    const newInstance = instantiate(element);
    parentDom.appendChild(newInstance.dom);
    return newInstance;
  }
  if (element == null) {
    // Nothing should be here anymore: remove.
    parentDom.removeChild(instance.dom);
    return null;
  }
  if (instance.element.type !== element.type) {
    // Different type: throw the whole subtree away and build a new one.
    const newInstance = instantiate(element);
    parentDom.replaceChild(newInstance.dom, instance.dom);
    return newInstance;
  }
  if (typeof element.type === "function") {
    // Same component: call it again and diff what it returns.
    instance.childInstance = reconcile(parentDom, instance.childInstance, renderComponent(element));
    instance.dom = instance.childInstance.dom;
    instance.element = element;
    return instance;
  }
  // Same DOM type: keep the node, patch its props, then diff its children.
  updateDom(instance.dom, instance.element.props, element.props);
  instance.childInstances = reconcileChildren(instance, element);
  instance.element = element;
  return instance;
}

(The real file also records each operation in a patches array so you can watch them. That's left out above.)

The last case is where all the savings come from. Same type means "the same thing as last time", so the existing DOM node is kept and only props that changed are written. That's why updateDom was written in chapter 4 to take prevProps: it skips every prop whose value is identical. Then it recurses into the children, matching them by position:

function reconcileChildren(instance, element) {
  const oldChildren = instance.childInstances;
  const newElements = element.props.children;
  const next = [];
  for (let i = 0; i < Math.max(oldChildren.length, newElements.length); i++) {
    const child = reconcile(instance.dom, oldChildren[i], newElements[i]);
    if (child) next.push(child);
  }
  return next;
}

Old child 0 with new child 0, old child 1 with new child 1. Extra new children are created, extra old ones removed.

One simplification to know about: in this stage a component must return exactly one element, because an instance tracks one DOM node. Fragments and null come back in chapter 7 when the toy moves to fibers.

Diffing two trees, step by step
Previous renderThis renderh1TodosliMilkliDogulp1 leftdivapph1TodosliMilkliWalk dogliReadulstrong2 leftdivapp darkDOM operationsnone yet
Step 1 of 9

Two element trees: what the last render returned (left) and what this one returned (right). The goal is the smallest set of DOM changes that turns the left into the right.

Now the chapter 4 counter again, on the stage 5 toy. Type in the box.

The reconciler keeps your input
import { createElement, render, patches } from "./toy.js";

let state = { count: 0, name: "" };
const root = document.getElementById("root");

function setState(next) {
  state = { ...state, ...next };
  patches.length = 0;
  render(<App {...state} />, root);
  console.log(patches.join("\n"));
}

function App({ count, name }) {
  return (
    <div>
      <button onClick={() => setState({ count: count + 1 })}>Clicked {count} times</button>
      <p>
        <input value={name} placeholder="Type your name" onInput={(e) => setState({ name: e.target.value })} />
      </p>
      <p>Hello, {name || "stranger"}</p>
    </div>
  );
}

setState({});
Nothing logged yet.

The first render is a single CREATE <App>: the whole tree, <div> and everything in it, was built off screen and inserted once. After that, a click is one text update. A keystroke updates the input's value and the greeting's text, and nothing else. The input is the same DOM node it was before, so it keeps focus. Same components as chapter 4, same "render everything" calls. The only change is that the renderer compares before it touches anything.

What each kind of change costs#

The patch log makes the rules visible. This sandbox renders a sequence of trees into the same container and prints what each step did.

Patches for different changes
import { createElement, render, patches } from "./toy.js";

const root = document.getElementById("root");
function show(label, element) {
  patches.length = 0;
  render(element, root);
  console.log(`${label}:\n  ${patches.join("\n  ") || "(nothing)"}`);
}

show("first render", <ul className="list"><li>Milk</li><li>Dog</li></ul>);
show("same tree again", <ul className="list"><li>Milk</li><li>Dog</li></ul>);
show("text change", <ul className="list"><li>Milk</li><li>Walk dog</li></ul>);
show("prop change", <ul className="list dark"><li>Milk</li><li>Walk dog</li></ul>);
show("append", <ul className="list dark"><li>Milk</li><li>Walk dog</li><li>Read</li></ul>);
show("prepend", <ul className="list dark"><li>Eggs</li><li>Milk</li><li>Walk dog</li><li>Read</li></ul>);
show("type change", <ol className="list dark"><li>Eggs</li><li>Milk</li><li>Walk dog</li><li>Read</li></ol>);
Nothing logged yet.

Read the output top to bottom:

  • Same tree again costs nothing. Every prop and text compares equal.
  • Text and prop changes are one operation each.
  • Append is one CREATE.
  • Prepend is the interesting one. Adding "Eggs" at the front shifts every item by one position, so position matching sees "Milk became Eggs, Walk dog became Milk, Read became Walk dog" and a new "Read" at the end: three text updates and a create, for what was one insertion. With text items that's only wasteful. With items that have their own state, like inputs or checkboxes, it attaches that state to the wrong item. That's the bug keys fix, in chapter 6.
  • Type change from <ul> to <ol> is a single REPLACE, and everything below it is rebuilt, even though all the <li>s are identical. That's rule 1 in action.

The real thing: reconciliation in React#

React applies the same rules, and you can see them in behavior.

Same type at the same position means "the same thing". The DOM node is kept and only changed props are written. For a component, the same function at the same position is the same component instance: React calls it again with new props, and its state survives.

A different type destroys the subtree. Everything below is unmounted, DOM nodes removed and component state thrown away, then the new subtree is mounted fresh. Try it: type something in the input below, then press the button, which swaps the wrapping <div> for a <section> and back. The input itself didn't change at all.

Changing a parent's type resets everything below it
<button id="swap">Swap the wrapper</button>
<div id="root"></div>

The text you typed is gone after every swap, because the <input> was destroyed along with its parent. That's the same REPLACE the toy logged for <ul> to <ol>. (The input is uncontrolled here, so its text lives only in the DOM node. Component state, which you'll meet in chapter 8, is lost the same way.)

What's different from the toy#

The rules match. The machinery doesn't:

  • React doesn't recurse like this anymore. Since React 16, reconciliation runs on fibers: one object per element, linked into a tree, processed in a loop that can pause between nodes. Chapter 7 rebuilds the toy that way.
  • There's no patch list. During the render phase, React marks fibers with flags (Placement, Update, ChildDeletion). The commit phase then walks the tree and applies the flagged work to the DOM in one go. The toy's patches array is only a log for you to read.
  • Children are matched by key first, then by position for unkeyed children, with a pass that detects moves (chapter 6). null, false and undefined children also keep their positions in React: {show && <Banner />} followed by <Form /> keeps Form at index 1 either way, so toggling the banner doesn't remount the form. The toy drops empty children, so it doesn't preserve that.
  • React can skip whole subtrees whose props and state haven't changed (bailouts), instead of re-rendering everything from the top.
  • The reconciler is platform-agnostic. The same diffing code (react-reconciler) drives react-dom, React Native and others. Only the "host config" that creates and updates nodes differs. That's the clean split the toy has between reconcile and createDom/updateDom.

The myth: "the virtual DOM is faster than the DOM"#

You'll hear it in interviews, blog posts and job descriptions. It's wrong as stated, and the precise version is a good answer to have ready.

The virtual DOM is extra work on top of the DOM, never instead of it. Every update, React re-runs components, creates a new element tree, and compares it with the old one. Then it makes the same DOM calls you would have made by hand. A hand-written update that knows exactly which node to change (li.className = "done") skips all of that and is always at least as fast.

What the virtual DOM is faster than is the naive declarative approach: rebuilding the DOM from scratch on every change, like chapters 2 and 4 did. Diffing lets you write code as if you re-render everything, and pay for roughly the DOM operations that actually changed. Here are all three on the same 3,000 rows:

Rebuild, diff, or patch by hand
<button id="rebuild">Toggle row 1: rebuild everything</button>
<button id="diff">Toggle row 1: diff</button>
<button id="hand">Toggle row 1: patch by hand</button>
<div id="root" style="height: 110px; overflow: auto"></div>
Nothing logged yet.

Click each a few times (timings are noisy, especially the first click). You'll see the same order everywhere: patching by hand is fastest, diffing is next, rebuilding is slowest. The diff spends its time in JavaScript, creating thousands of element objects and comparing them with the previous ones, to produce exactly the one DOM write the hand-written version made directly.

So the honest claim is about trade-offs, not raw speed:

  • You get declarative code (view(state)) with performance that's good enough for most UIs, without writing update code by hand.
  • You pay a cost proportional to the size of what re-renders, not to what changed. That's why React gives you ways to re-render less (chapter 29 covers memoization, and the React Compiler in chapter 30 does it automatically).
  • Other frameworks make a different trade. Svelte compiles components into direct DOM updates, and Solid tracks fine-grained dependencies (signals) so a change runs only the code that depends on it. Neither diffs a virtual tree. Chapter 37 compares the approaches.

Pitfalls#

Check your understanding#

Fix itThe field that forgets

Type a name into the field, then press Tick. The name disappears. Fix it without changing what's rendered, so that typed text survives re-renders. Press Check when you think it works.

import { createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root"));

function App({ ticks }) {
  function NameField() {
    return <input aria-label="Name" placeholder="Name" />;
  }

  return (
    <div>
      <p>Ticks: {ticks}</p>
      <NameField />
      <button onClick={() => draw(ticks + 1)}>Tick</button>
    </div>
  );
}

function draw(ticks) {
  root.render(<App ticks={ticks} />);
}

draw(0);
PredictTwo different inputs?

In real React, you type "hello" into the input, then isAdmin flips from false to true. What does the input show?

function Login({ isAdmin }) {
  return (
    <form>
      {isAdmin ? <input placeholder="Admin code" /> : <input placeholder="User name" />}
    </form>
  );
}
Quick checkWhy O(n)

How does React keep diffing linear instead of O(n³)?

Explain it out loudExplain reconciliation

An interviewer asks: "How does React decide what to update in the DOM? And is the virtual DOM faster than the real DOM?"

Interview angle

Say it in 30 seconds

On every update React re-runs components to get a new element tree and reconciles it with the previous one, applying only the differences to the DOM. A general tree diff is O(n³), so React uses two heuristics to do it in one linear pass: elements of different types produce different subtrees, so a type change destroys and remounts everything below; and children are matched by key, or by position without one. Same type and key means the same DOM node or component instance, so its state survives. The virtual DOM isn't faster than the DOM; it's overhead that makes declarative code cheap enough.

How does React's reconciliation (diffing) algorithm work?

intermediate

Is the virtual DOM faster than the real DOM?

intermediate

What happens to a component's state if its parent element changes from a div to a section?

intermediate

Why shouldn't you define a component inside another component?

basic

Does a component re-rendering mean the DOM was updated?

basic

Does React compute a list of patches when it diffs?

senior

Recap#

  • Reconciliation compares the new element tree with the previous one and applies only the differences. A general tree diff is O(n³); React's is O(n).
  • Two heuristics make that possible: different types mean different subtrees (no comparison inside), and children match by key, or by position without keys.
  • Same type at the same position keeps the DOM node or component instance, with its state; only changed props are written. A type change destroys and remounts everything below.
  • Position matching makes insertions at the front expensive and, for stateful items, wrong. Keys fix it (chapter 6).
  • The virtual DOM isn't faster than the DOM. It's overhead that lets you write declarative code while keeping DOM work close to what changed.

Sources#