Frontend Case Studies

Topic F3

The DOM and virtual DOM diffing

How React compares two trees, and why keys decide how much of the DOM changes.

9 min · intermediate

Watch: one new item is added at the top of a list. Without labels, every item is rewritten; with labels, just one is added.

oldnewABCXABC
  • moving now
  • being checked
  • passed / marked
Step 1 of 6

The old list is A, B, C. State changes and the new list is X, A, B, C (X added at the top). React compares the two to find the fewest DOM changes.

React looks for the fewest DOM changes. Keys tell it which elements are the same in both lists.

React's two rules

  • Different types mean different trees: if a <div> becomes a <section>, or component A becomes component B, React throws away the whole old branch (state included) and builds a new one. It doesn't try to match what's inside.
  • Children are matched by key: within a list, React uses key to know which element is the same across the old and new renders. Without keys, it matches by position.

Why key={index} causes trouble

An index is a position. Insert a new item at the top and every item gets a new index, so React thinks they all changed. Worse, state tied to the position (half-typed text in an input, a ticked checkbox, focus) stays at the old position and is now attached to the wrong item. Choose "no keys" in the figure: inserting one item touches all four elements.

Code, for programmersStable keys
// bad when the list can be reordered, filtered or prepended
{todos.map((todo, i) => <TodoRow key={i} todo={todo} />)}

// good: an id that belongs to the data and never changes
{todos.map((todo) => <TodoRow key={todo.id} todo={todo} />)}

// also bad: a new key on every render forces a full rebuild each time
{todos.map((todo) => <TodoRow key={Math.random()} todo={todo} />)}

An index is only safe if the list is never reordered, filtered or inserted into, and its items hold no state of their own.

Quiz

  1. A list uses key={index}. A new item is inserted at position 0. What happens?

  2. A <Chart> component becomes a <Table> in the same spot. What does React do?

  3. The best key for a list of orders?

0 of 3 answered.