Skip to main content
12

Virtual DOM and reconciliation: why does key matter?

MediumReactVirtual DOMReconciliation

What is the Virtual DOM, how does React's reconciliation work, and why does the key prop matter?

TL;DR

When state changes, React re-runs your components to get a new tree of elements (the Virtual DOM), diffs it against the previous tree, and applies only the needed changes to the real DOM. That diff is reconciliation. To keep it fast (O(n) instead of O(n³)), React assumes two things: elements of different types produce different trees, and key identifies which list items are the same across renders.

Key points

  • Same type at the same position: React keeps the DOM node and component state and updates props.
  • Different type (<div> → <span>, or ComponentA → ComponentB): React tears down the subtree, state included, and builds a new one.
  • Keys must be stable and unique among siblings, ideally an ID from the data.
  • Using the array index as a key breaks when items are inserted, removed or reordered: state (input values, focus) sticks to the wrong item.
  • Changing a component's key on purpose is a clean way to reset its state.
  • Fiber lets React split rendering into units of work so urgent updates (typing) can interrupt less urgent ones.

Example

jsx
// Bug: index keys. Delete the first row and its input text moves to the next row
{
  todos.map((todo, i) => <TodoRow key={i} todo={todo} />)
}

// Correct
{
  todos.map((todo) => <TodoRow key={todo.id} todo={todo} />)
}

// Reset a form when the selected user changes
;<ProfileForm key={userId} userId={userId} />

Common follow-ups

  • Is the Virtual DOM faster than direct DOM updates? Not inherently. Its value is a declarative model with good-enough updates; hand-tuned DOM code can be faster.
  • When is index as a key fine? For static lists that never reorder and hold no state.

What interviewers look for

Tip

Explain render → diff → commit, the two heuristics, and a concrete index-key bug.

  • Red flag: "the Virtual DOM re-renders the whole page", or key={Math.random()}.

Was this helpful?

Related questions