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 calls your component functions and a commit applies changes to the DOM. Here you will learn how React decides which changes to make after a render.
The problem reconciliation solves
A component returns a description of the UI, which is a tree of React elements. After a state change, React calls your components again and gets a new tree. The screen already shows the old tree. React has to turn the old DOM into the new one with as few DOM operations as it can.
Reconciliation is the process of comparing the previous element tree with the next one and working out what changed. The result is a list of changes. The commit phase then applies that list to the DOM.
Finding the smallest set of edits between two arbitrary trees is expensive. The best known general algorithms take roughly cubic time in the number of nodes. For a tree of 1,000 nodes, that means on the order of a billion comparisons. React avoids this cost by using two assumptions that hold for almost all real UIs.
The two heuristics
React's diffing relies on these rules:
- Two elements of different types produce different trees. React does not try to find similarities between them.
- The developer can hint which child elements are stable across renders by supplying a
key.
With these rules React compares the trees in a single pass, in time linear in the number of nodes. The trade-off is that React sometimes rebuilds more than strictly necessary. It never produces a wrong result because of this.
Comparing at the root: the type check
React starts at the root of the tree and compares the old and new element at each position. The first question is always whether the two elements have the same type.
Different types: tear down and rebuild
If the type differs, React discards the old subtree and builds a new one. For DOM elements, a type is the tag name. For components, it is the function itself.
Consider a change from <div> to <section>:
// Before
<div>
<Counter />
</div>
// After
<section>
<Counter />
</section>React sees div replaced by section. It removes the old DOM node and everything inside it. Every component below it is unmounted, which means its state is destroyed and its cleanup effects run. React then creates a new section node and mounts a fresh Counter with initial state.
The same applies to components. Changing <A /> to <B /> at the same position unmounts A and mounts B, even if both render identical markup.
Same type DOM elements: update attributes
If both elements are the same DOM type, React keeps the existing DOM node. It compares the props and updates only those that changed.
// Before
<div className="before" title="stuff" />
// After
<div className="after" title="stuff" />Here React updates className on the existing div and leaves title alone. For the style prop, React compares the individual style properties, so changing color does not reset fontSize.
After updating the node, React recurses into its children.
Same type components: update and re-render
If both elements are the same component type, the instance stays mounted. Its state is preserved. React gives it the new props and calls the component function again, which produces a new subtree. Reconciliation then continues down into that subtree.
This is why state survives re-renders: the component at that position has the same type, so React treats it as the same instance.
Recursing into children
After comparing a parent, React compares its children. The default behavior walks both child lists at the same time, from the first child to the last, comparing the child at index 0 with the child at index 0, then index 1 with index 1, and so on.
Appending to the end of a list works well with this approach:
// Before
<ul>
<li>first</li>
<li>second</li>
</ul>
// After
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>React matches the first two li elements, finds no changes, and inserts a new li for the third. This is cheap.
Inserting at the start is a problem:
// Before
<ul>
<li>Duke</li>
<li>Villanova</li>
</ul>
// After
<ul>
<li>Connecticut</li>
<li>Duke</li>
<li>Villanova</li>
</ul>Compared by position, React sees Duke become Connecticut, Villanova become Duke, and a new li added for Villanova. It mutates two text nodes and creates one element, when the better answer is to insert a single element at the front. For plain li elements this only wastes work. For components that hold state, it causes real bugs, because state stays attached to the position and not to the data. The next chapters cover how keys fix this.
A worked example: watching the diff
You can observe the type rule directly. This component swaps between two element types at the same position and logs when the child mounts.
import { useEffect, useState } from 'react';
function Child({ label }) {
useEffect(() => {
console.log('Child mounted:', label);
return () => console.log('Child unmounted:', label);
}, [label]);
return <p>{label}</p>;
}
export default function App() {
const [wrapped, setWrapped] = useState(false);
return (
<>
<button onClick={() => setWrapped(w => !w)}>Toggle wrapper</button>
{wrapped ? (
<section>
<Child label="inside" />
</section>
) : (
<div>
<Child label="inside" />
</div>
)}
</>
);
}Click the button and watch the console. Each click logs an unmount and a mount for Child, even though Child receives identical props. The parent element type changed from div to section, so React discarded the whole subtree. If both branches used div, the console would stay quiet after the first mount, because React would update the existing node and keep Child.
In React Strict Mode during development, effects also run an extra mount and unmount cycle on the first mount. Expect extra log lines on initial load that are unrelated to the diff.
What the diff produces
The reconciler does not touch the DOM while it compares. It records the work to do, such as inserting a node, updating a prop, or removing a subtree. The commit phase later applies these changes in one go. This is why the render phase can be paused or discarded, a property that concurrent rendering uses.
The diagram shows the decision React makes for each pair of elements at the same position.
Common errors and gotchas
Defining a component inside another component
A component defined inside another component's body is a new function on every render. React compares function identity as the type, so it sees a different type each time and remounts the child on every render. Its state resets and inputs lose focus.
function Parent() {
// Wrong: Inner is a new function on each render
function Inner() {
return <input />;
}
return <Inner />;
}Define Inner at module level instead.
Changing wrapper elements by condition
Wrapping a child in an extra element only in some cases changes the child's position in the tree. The child's type may match, but its parent chain differs, so React remounts it. Keep the structure stable and change props or styles instead.
Assuming a re-render means a DOM update
A component can re-render and produce an identical tree. Reconciliation then finds nothing to change and the commit makes no DOM updates. A render is not the same as a DOM change. Re-rendering costs CPU time for your functions and the diff, but it does not by itself cause layout or paint work.
Expecting React to detect moved subtrees
Without keys, React does not notice that a subtree moved to another position. It sees a type change or a prop change at each index. Moving a stateful component to a different parent always resets its state.
Summary of rules
| Situation at one position | What React does | State of the component |
|---|---|---|
| Different element type | Unmount old subtree, mount new one | Destroyed, new state starts fresh |
| Same DOM element type | Update changed attributes on the existing node | Children are compared next |
| Same component type | Call the function with new props | Preserved |
| Child added at the end of a list | Insert a new node | Existing children untouched |
| Child inserted at the start without keys | Mutate every shifted position | Attached to positions, not data |
Exercise
A component renders <div><Form /></div> when compact is true and <section><Form /></section> when it is false. Form holds the text a user typed in an input. What happens to that text when compact changes, and what change would preserve it?
Show answer
The text is lost. The parent element type changes from div to section, so React unmounts the old subtree, including Form and its state, and mounts a new Form with initial state. To keep the text, use the same element type in both branches, for example <div className={compact ? 'compact' : 'full'}><Form /></div>, so React updates the existing node and keeps Form mounted.
Exercise
Why does React use a heuristic diff instead of finding the minimum set of edits between two trees, and what are the two assumptions it relies on?
Show answer
A general minimum tree edit algorithm takes roughly cubic time in the number of nodes, which is too slow for UI updates. React makes it linear by assuming that elements of different types produce different trees, and that keys can mark which children stay stable between renders. The cost is that React sometimes rebuilds a subtree that a smarter algorithm would have reused.