Chapter 1React · Theory

Virtual DOM & Reconciliation

React keeps a lightweight copy of the page structure in memory and uses it to figure out the smallest number of real DOM changes needed.

The virtual DOM (VDOM) is a plain JavaScript object that describes what the real DOM should look like. When state changes, React builds a new VDOM and compares it to the previous one. This comparison process is called reconciliation (or diffing).

The comparison follows two rules: (1) if the element type changes (e.g. a div becomes a span), React throws away the old tree and builds a new one; (2) if the element has a stable key, React reuses the existing DOM node instead of replacing it. This lets React figure out the smallest set of real DOM changes needed, then applies them all at once.

React 18 adds automatic batching — when you call setState multiple times in a row (even inside a setTimeout or Promise), React groups them into a single re-render instead of running one per call. The virtual DOM adds some overhead for very simple pages, but it significantly cuts down on expensive real DOM work for complex, frequently-updating UIs.

State change
     ↓
New VDOM tree
     ↓
Diff (reconcile) with previous VDOM
     ↓
Minimal DOM patches
     ↓
Real DOM update (one flush)
Diagram: Virtual DOM & Reconciliation