Virtual DOM in React
Virtual DOM is a lightweight copy of the real DOM stored in RAM.
React updates this copy instead of directly modifying the real DOM to avoid triggering unnecessary "expensive" operations (layout, painting, reflow) in the browser.
When all changes are made, React compares old and new versions of Virtual DOM (diffing) and precisely updates the real DOM (reconciliation).
Heuristic O(n) Algorithm
React applies an efficient algorithm with two key assumptions:
-
Different element types → different trees
- Two elements with different types will produce different trees. When comparing two trees, React first compares two root elements. When root elements have different types, React destroys the old tree and builds a new one from scratch.
- If type doesn't change, only changed attributes and child nodes are updated.
-
keyvalue for children- When reordering elements in a list, keys (
key) allow React to understand which elements persisted, which were added and which were removed. - This saves resources and reduces re-renders.
- When reordering elements in a list, keys (
Update Steps (simplified)
-
Virtual DOM Update
React captures changes (e.g.,setStateoruseStatecall). -
Diffing
React compares previous Virtual DOM with new one, identifying differences. -
Reconciliation
- Only changed parts of real DOM are re-rendered.
- Updates are performed in batches, not after each small change.
Key Points
- Minimizing real DOM work: React minimizes "expensive" browser operations.
- Encapsulation: Components work with their state without manual control over reflow/layout.
- Easy scaling: Algorithm allows writing more scalable and maintainable code.
Important nuance:
If parent component renders, by default its child components also re-render unless additional optimizations are applied (React.memo, shouldComponentUpdate, etc.)