Virtual DOM
A lightweight in-memory JavaScript representation of the real DOM tree used to compute minimal DOM mutation diffs.
Mental Model
"The Blueprint: Before rebuilding a skyscraper wall, architects test changes on a digital 3D model (vDOM) to avoid expensive physical demolition."
Interactive Engine Simulation
React only updates the second node (highlighted) because only that part of the state changed. This avoids re-painting the entire UI.
Executable Code Snippet
1// This JSX isn't HTML.
2// It's a lightweight JS object.
3const vnode = {
4 type: 'div',
5 props: {
6 className: 'container',
7 children: 'Hello World'
8 }
9};- 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. Why the Virtual DOM?
The Real DOM (Document Object Model) is a heavy C++ object in the browser. Changing one pixel can trigger a **reflow** or **repaint** of the entire page. React avoids this by keeping a "virtual" copy of the tree in memory. Memory (RAM) is thousands of times faster than DOM manipulation.
The VDOM Process
02. Reconciliation
Reconciliation is the process of comparing the old VDOM tree with the new one. React uses a **Heuristic Diffing Algorithm** that assumes if two elements have different types, they will produce different trees. This allows it to find changes in O(n) time instead of O(n³).
Developer Note
The Virtual DOM is why "Keys" are so important. They help React match old virtual nodes to new ones, preventing unnecessary unmounting and re-mounting of expensive components.