How React Virtual DOM Works Under the Hood
Direct DOM manipulation is slow. Updating the screen directly forces the browser to recalculate layouts and repaint pixels. Do this too often, your app lags.
React solves this. How? The Virtual DOM.
The Problem: Real DOM is Expensive
The Real DOM is the actual browser API. It manages the HTML you see.
Updating it is slow.
It triggers heavy layout recalculations.
Changing 10 items makes the browser redraw the page 10 times.
We need a faster way.
Real DOM vs Virtual DOM
Real DOM: Heavy browser objects. Slow to update.
Virtual DOM (VDOM): Lightweight JavaScript objects. Fast to create and compare.
Think of the VDOM as a blueprint. The Real DOM is the actual house. It is cheaper to change a blueprint than to tear down walls.
Step 1: Initial Render
Your component loads for the first time.
React reads your JSX.
Builds a VDOM tree (the blueprint).
Converts VDOM to Real DOM.
Browser paints the screen.
Component JSX → Virtual DOM → Real DOM → Screen
Step 2: State or Props Change
User clicks a button. State updates.
React does not touch the Real DOM yet. Instead:
React re-runs your component function.
Generates a brand new VDOM tree.
State Update → Component Re-runs → New Virtual DOM Tree
Step 3: Diffing (Reconciliation)
Now React has two blueprints:
Old VDOM (before click)
New VDOM (after click)
React compares them. This is diffing (or reconciliation).
It looks for differences. Did text change? Did a class name change? Did a list item disappear? React finds the exact, minimal changes needed.
Old VDOM Tree ←→ New VDOM Tree
↓
Find Differences
↓
Calculate Minimal Patch
Step 4: Updating the Real DOM
React knows exactly what changed. It updates only those specific nodes in the Real DOM.
If only one button's text changed, React updates one text node. It ignores the rest of the page.
Minimal Update Patch → Applied to Real DOM
Why This Improves Performance
JS is fast: Creating and comparing JS objects takes milliseconds.
DOM is slow: Touching the browser API takes time.
Batching: React groups updates. Real DOM updates once per cycle.
No wasted work: Unchanged parts of the UI stay untouched.
The Full Flow: Render → Diff → Commit
Here is the high-level mental model. No deep internals needed.
Render: Build the new Virtual DOM tree.
Diff: Compare old tree with new tree. Find the patch.
Commit: Apply the patch to the Real DOM.
[Render Phase]
Component → New Virtual DOM
[Diffing Phase]
Old VDOM vs New VDOM → Diff Algorithm
[Commit Phase]
Minimal Updates → Real DOM → Browser Paints
Quick Takeaway
Real DOM updates are slow and expensive.
Virtual DOM is a fast, lightweight JS copy.
State changes trigger a new VDOM tree.
React diffs the old and new trees.
Only minimal, necessary changes hit the Real DOM.
Result: Fast, smooth UI updates.

