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 Walkthrough
Reference 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.Virtual DOM objects are cheap JavaScript objects living in heap memory.
- 02.React diffs the new vDOM tree against the previous vDOM tree during the render phase.
- 03.Only the exact changed DOM properties/nodes are committed to the real browser DOM.
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.