How does React's reconciliation (diffing) algorithm work?
Hint
Comparing two trees in general is O(n³). Which two assumptions let React do it in O(n)?
Full Answer
Reconciliation is how React works out what changed between the previous render's element tree and the new one, so it can update only that part of the DOM. A general tree diff is O(n³); React makes it O(n) with two assumptions:
- Different type → different tree. If an element's type changes (
<div>to<section>, orComponentAtoComponentB), React destroys the old subtree, state included, and builds a new one. - Keys identify children. In a list, React matches old and new children by
key, so it can move, add or remove items instead of re-creating them.
// Same type: React keeps the DOM node and updates only className
<div className="old" /> → <div className="new" />
// Stable keys: inserting at the top moves nothing else
{todos.map(todo => <Todo key={todo.id} todo={todo} />)}
// ❌ Index keys: inserting at the top shifts every key,
// so state (like input text) ends up on the wrong item
{todos.map((todo, i) => <Todo key={i} todo={todo} />)}
Reconciliation decides what changes; rendering a component still runs its function. To skip re-rendering a subtree whose props didn't change, use React.memo.
💡 Changing a component's
key is a deliberate way to reset its state: React treats it as a new component.More React Fundamentals Questions
Practice this in a timed sprint
5 free questions, no signup required