Sub topic 6
Reconciliation: how React compares two trees
This chapter assumes you know JavaScript functions, objects, and arrays, basic React components, props, and JSX, the useState hook, and the browser DOM. It also assumes you know that a render produces a tree of elements, and that React then commits changes to the DOM.
The problem reconciliation solves
After a state change, React calls your components again and gets a new tree of elements. The DOM already shows the old tree. React must work out the smallest set of DOM changes that turns the old tree into the new one. This comparison is called reconciliation.
An element is a plain object that describes what you want on screen, such as { type: 'button', props: {...} }. Creating elements is cheap. Changing the DOM is the costly part, so React compares the two element trees and touches the DOM only where they differ.
Two assumptions that keep it fast
A general algorithm that finds the minimum edits between two arbitrary trees takes roughly cubic time in the number of nodes. That is too slow for UI. React instead uses a heuristic that runs in linear time, based on two assumptions:
- Elements of different types produce different trees. React does not try to match them.
- Within a list of children, a
keyprop tells React which child is which across renders.
React walks both trees from the root, comparing nodes at the same position level by level. It never searches for a node that moved to a different parent.
The comparison rules
At each position, React compares the old element with the new one.
| Case | What React does |
|---|---|
| Different `type` (for example `div` becomes `span`, or `A` becomes `B`) | Unmounts the old subtree, destroying its DOM nodes and state. Mounts a new subtree. |
| Same DOM element type | Keeps the DOM node. Updates only the attributes that changed, then recurses into the children. |
| Same component type | Keeps the component instance and its state. Calls it with the new props, then compares what it returns. |
The third row is why state survives a re-render. The component is the same type at the same position, so React reuses it.
Reconciling children
When React compares a list of children, it first looks at them in order. If you append an item to the end, React sees the old items unchanged and one new item, so it only inserts one node.
Inserting at the start is a problem without keys. Every position now holds a different item than before, so React updates every node instead of moving them. With keys, React matches children by key, sees that the existing items only shifted, and inserts a single node. Keys are covered fully in a later chapter.
A worked example
import { useState } from 'react';
function Field({ label }) {
const [text, setText] = useState('');
return (
<label>
{label}
<input value={text} onChange={e => setText(e.target.value)} />
</label>
);
}
function Form() {
const [showHint, setShowHint] = useState(false);
return (
<div>
{showHint ? <p>Use your full name.</p> : null}
<Field label="Name" />
<button onClick={() => setShowHint(!showHint)}>Toggle hint</button>
</div>
);
}Type something into the field, then click the button. You would expect the text to survive, and it does. React keeps a slot for each child even when the value is null. Field stays in the second slot whether the hint is present or not, so its type and position match and its state is kept.
Common errors
- Defining a component inside another component. Each render creates a new function, so React sees a different type at that position. It unmounts and remounts the inner component every time, which loses its state and focus.
- Assuming a re-render means DOM work. Rendering a component only produces elements. If the result is identical, reconciliation finds nothing to change and the DOM is untouched.
- Expecting React to detect moved subtrees. If you move a component to a different parent, React treats it as a removal and a new mount.
Exercise
A component renders <Counter /> inside a <div>. After a state change it renders <Counter /> inside a <section> instead. Is the Counter's state kept? Why?
Show answer
No. The parent changed type from div to section, so React unmounts the whole old subtree and mounts a new one. The Counter is created fresh and its state resets to the initial value.
Exercise
Why does React compare only nodes at the same position instead of searching for the best match across the whole tree?
Show answer
Finding the minimum edits between arbitrary trees takes about cubic time, which is too slow for UI. Comparing by type and position (plus keys in lists) takes linear time and works well for typical UI changes.