Reconciliation
The diffing algorithm React uses to compare the old and new Virtual DOM trees and calculate minimal DOM updates.
Mental Model
"Spot the Difference: Comparing two nearly identical cartoon panels and marking only the 2 altered pixels with red ink."
Interactive Engine Simulation
Executable Code Snippet
1// Old Tree: <div><p>Hello</p></div>
2// New Tree: <div><span>Hello</span></div>
3
4// Reconciliation detects the type change
5// (p -> span) and destroys the old subtree.- 01.Component re-renders are triggered by state or prop changes.
- 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
- 03.Automatic batching optimizes multiple state updates into a single render cycle.
01. Heuristic O(n)
Generic tree-diffing algorithms are O(n³). For 1000 nodes, this would take a billion comparisons. React uses two simple **heuristics** to bring this down to O(n): 1. Two elements of different types will produce different trees. 2. Developers can hint which elements are stable across renders with a 'key'.
Diffing Logic
- Same Type? Update Props
- Different Type? Destroy & Rebuild
- List without Key? Re-order by Index
02. Tearing Down the DOM
If a component type changes (e.g. from `<Header />` to `<Footer />`), React doesn't try to compare them. It tears down the entire subtree, runs all cleanup effects, and builds the new tree from scratch. This is why keeping component types stable is critical for performance.
Internal Secret
"Keys are the only way to override the type-based destruction. By changing a key on a component, you can force React to treat it as a totally new instance, resetting its state and effects."