惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
宝玉的分享
宝玉的分享
Jina AI
Jina AI
IT之家
IT之家
博客园 - Franky
MyScale Blog
MyScale Blog
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
雷峰网
雷峰网
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
Google DeepMind News
Google DeepMind News
美团技术团队
S
SegmentFault 最新的问题
罗磊的独立博客
博客园 - 聂微东
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
D
Docker
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How React's Virtual DOM Works Under the Hood
Janmejai Sin · 2026-05-22 · via DEV Community

How React's Virtual DOM Works Under the Hood

You've heard it a hundred times: "React uses a Virtual DOM for performance."

But what does that actually mean?

In this article, we'll trace exactly what happens from the moment you call setState() to the moment you see pixels update on screen — no hand-waving, no magic, just the mental model that unlocks everything else in React.

Let's dig in. 🛠️


The Problem: Why Direct DOM Manipulation Is Slow

Before we understand the solution, we need to understand the problem.

The browser's DOM (Document Object Model) is a live, tree-shaped object that represents your HTML page. Whenever JavaScript changes a DOM node, the browser has to do expensive work:

  • Style recalculation — which CSS rules now apply?
  • Layout / Reflow — what is every element's new size and position?
  • Repaint — what pixels need to be redrawn?
Direct DOM Update:
─────────────────
JS writes to DOM
     │
     ▼
Style Recalc → Layout (Reflow) → Paint → Composite
                    ↑
               ALL of this, potentially,
               for a single text change 😬

Enter fullscreen mode Exit fullscreen mode

This is fine for occasional updates. But modern web apps update the UI constantly — typed characters, live data feeds, animations. At high frequency, direct DOM manipulation becomes a bottleneck that shows up as janky, sluggish UIs.


The Solution: Virtual DOM as a Lightweight Proxy

React introduces the Virtual DOM: a plain JavaScript representation of the UI tree that exists purely in memory, completely decoupled from the browser's rendering engine.

// This is a Virtual DOM node. It's just a JS object.
{
  type: 'button',
  props: {
    className: 'btn-primary',
    onClick: handleClick,
    children: 'Click me'
  }
}

Enter fullscreen mode Exit fullscreen mode

Creating this object costs almost nothing. No browser APIs. No layout. No paint. It's just memory allocation.

React's insight: compute changes cheaply in JS-land first, then apply the minimal real-DOM mutations in one go.


Step 1 — Initial Render

When your app first loads:

JSX / Components
      │
      │  (Babel compiles JSX to React.createElement calls)
      ▼
Virtual DOM Tree
(plain JS objects, built entirely in memory)
      │
      │  (React walks the tree and creates real nodes)
      ▼
Real DOM  ←  User sees the UI ✅

Enter fullscreen mode Exit fullscreen mode

React calls your component functions, collects the returned JSX (which becomes React.createElement() calls), and assembles a full Virtual DOM tree. It then makes a single full pass to create and insert real DOM nodes.

This is the only time React builds the entire DOM from scratch.


Step 2 — State or Props Change

Something triggers an update:

const [count, setCount] = useState(0);

// Button clicked:
setCount(count + 1);  // 🔔 React queues a re-render

Enter fullscreen mode Exit fullscreen mode

setCount doesn't immediately update the DOM. React schedules an update and may batch it with other pending updates for efficiency. Then it moves into the render phase.


Step 3 — New Virtual DOM Tree is Created

React re-runs your component function with the new state. The result is a brand new Virtual DOM tree in memory:

 OLD Virtual DOM          NEW Virtual DOM
 ───────────────          ───────────────
 <div>                    <div>
   <h1>Score</h1>   vs      <h1>Score</h1>
   <span>0</span>           <span>1</span>  ← CHANGED
   <button>+</button>       <button>+</button>
 </div>                   </div>

Enter fullscreen mode Exit fullscreen mode

Both trees exist in memory simultaneously. React needs to figure out what's different.


Step 4 — Diffing (Reconciliation)

React's diffing algorithm compares the two trees node-by-node to produce a minimal change set.

Comparing node by node:

  <div>        ✅ Same type → keep, recurse into children
  <h1>Score</h1>  ✅ Same type, same props → NO CHANGE
  <span>       ✅ Same type → check props
    "0" → "1"  ❌ Text content changed → MARK FOR UPDATE
  <button>+</button>  ✅ Same type, same props → NO CHANGE

Change set: [ updateTextContent(spanNode, "1") ]

Enter fullscreen mode Exit fullscreen mode

React uses two key heuristics to keep this efficient:

Different element types → rebuild the subtree

If a <div> becomes a <section> at the same position, React doesn't try to reuse it. It destroys the old subtree and builds a new one.

Keys → stable identity for list items

// ❌ Bad — React can't tell which item is which after reorder
{items.map(item => <li>{item.name}</li>)}

// ✅ Good — React can match, reuse, and correctly update items
{items.map(item => <li key={item.id}>{item.name}</li>)}

Enter fullscreen mode Exit fullscreen mode

Keys let React correlate old list nodes with new ones. Without them, React might destroy and re-create nodes it could have reused — wasting work and losing local state (like focus or scroll position).


Step 5 — Commit Phase: Minimal Real DOM Updates

Once the diff is done, React enters the commit phase — the only point where it writes to the real DOM:

Change set from diff:
┌──────────────────────────────────────┐
│  • Update text of <span>: 0 → 1     │
│  (1 operation total)                 │
└──────────────────────────────────────┘
         │
         ▼
  Real DOM ← only the <span>'s text node is touched
  Everything else: untouched, no reflow triggered 🎯

Enter fullscreen mode Exit fullscreen mode

Compare this to a naive approach that re-renders the entire list after every keystroke. With React, only the nodes that actually changed are touched.


Why This Improves Performance

Approach What Happens on Update
Direct DOM manipulation Write immediately → browser reflows everything potentially affected
React Virtual DOM Diff in memory → write only changed nodes → minimal browser work

The Virtual DOM isn't magic. Creating JS objects has a cost too. The real win is batching and minimization: React figures out the cheapest path from the current UI to the desired UI, then executes it in one optimized burst.


The Full Lifecycle — Visual Summary

┌────────────────────────────────────────────────────────┐
│            REACT: RENDER → DIFF → COMMIT               │
│                                                        │
│  setState() / new props                                │
│       │                                                │
│       ▼                                                │
│  ┌─────────────────────────────────────┐               │
│  │         RENDER PHASE                │               │
│  │  Component functions run            │               │
│  │  New Virtual DOM tree built         │               │
│  └──────────────┬──────────────────────┘               │
│                 │                                      │
│                 ▼                                      │
│  ┌─────────────────────────────────────┐               │
│  │      RECONCILIATION (DIFF) PHASE    │               │
│  │                                     │               │
│  │  Old VDOM ◄──── compared ────► New VDOM             │
│  │  Minimal change set computed        │               │
│  └──────────────┬──────────────────────┘               │
│                 │                                      │
│                 ▼                                      │
│  ┌─────────────────────────────────────┐               │
│  │         COMMIT PHASE                │               │
│  │  Only changed nodes written to DOM  │               │
│  │  useLayoutEffect runs               │               │
│  └──────────────┬──────────────────────┘               │
│                 │                                      │
│                 ▼                                      │
│  Browser paints minimal changes ✅                     │
│  useEffect runs                                        │
└────────────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode


Quick Reference: Key Concepts

Concept What It Means
Virtual DOM Plain JS object tree mirroring the UI — cheap to create
Re-render React calling your component function again to get new VDOM
Diffing Comparing old VDOM vs new VDOM to find changes
Reconciliation The full process: diff + decide what to update
Commit The moment React writes to the real DOM
Key Stable identity hint for list items during diffing

Things to Know (But Out of Scope Here)

  • React Fiber — React's internal concurrent scheduler that adds priority lanes and time-slicing on top of this model
  • React 18 Concurrent ModeuseTransition and useDeferredValue let you mark updates as non-urgent
  • React.memo — skips re-render (and therefore skips VDOM creation) when props haven't changed

Wrapping Up

React's Virtual DOM is elegant in its simplicity: represent the UI as cheap JS objects, compare states, compute minimal mutations, apply them. The render → diff → commit pipeline is the foundation of React's performance story — and once you have this mental model, concepts like key, memo, and concurrent features all start making intuitive sense.

If this clicked for you, follow along — next up we're diving into React Keys deep dive and why index-as-key breaks your app in surprising ways.

Happy coding! ⚛️


Tagged: #react #javascript #webdev #beginners