All topics
Performanceadvanced

The Reconciliation Diffing Algorithm

Understand the specific heuristics React's diffing algorithm uses to efficiently compare two element trees.

React's reconciliation algorithm is a heuristic, not a theoretically optimal tree-diff (a fully general tree-diff algorithm is O(n³), too slow for UI updates), built on two practical assumptions that hold true for the vast majority of real UI trees: elements of different types produce substantially different trees (so React doesn't try to diff their children at all, it tears down the old subtree and builds a new one), and keyed children provide identity across renders, letting React match and reorder items instead of rebuilding them.

React's diffing heuristic is like a moving crew that, when told 'the item at this spot in the truck used to be a couch and is now a bookshelf,' doesn't try to salvage any couch parts for the bookshelf — they just remove the couch entirely and bring in a fresh bookshelf; but if told 'it's still a couch, just reupholstered,' they keep the same couch frame in place and only swap the fabric.

Key Concepts

1
When comparing two elements at the same tree position, React first checks their type: if the type differs (a <div> became a <span>, or ComponentA became ComponentB), React destroys the old subtree entirely — including unmounting all its component instances and losing all their state — and builds the new subtree from scratch, rather than attempting to diff their internals at all. If the type is the same, React keeps the existing DOM node/component instance and only updates the changed attributes or props, preserving the underlying instance and its state.
<div><span>ComponentAComponentB
2
For lists of children, React uses the key prop specifically to identify which children persisted, were added, or were removed across renders, rather than assuming children at the same array index correspond to each other — this is exactly why stable, data-derived keys (not array indices) are essential for correct behavior when lists can reorder.
key
3
Interviewers exploring deeper React internals ask candidates to explain what happens to a component's internal state if its parent conditionally renders a different component type in its place (state is lost, since the type change causes the whole subtree to be torn down and rebuilt) versus conditionally rendering the same component type with different props (state is preserved, since only props/attributes are diffed and updated).