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

推荐订阅源

雷峰网
雷峰网
N
Netflix TechBlog - Medium
博客园_首页
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Y
Y Combinator Blog
腾讯CDC
V
V2EX
Microsoft Security Blog
Microsoft Security Blog
大猫的无限游戏
大猫的无限游戏
Cyberwarzone
Cyberwarzone
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
Schneier on Security
Schneier on Security
Microsoft Azure Blog
Microsoft Azure Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News: Ask HN
Hacker News: Ask HN
Martin Fowler
Martin Fowler
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
U
Unit 42
WordPress大学
WordPress大学
N
News and Events Feed by Topic
S
Schneier on Security
T
The Blog of Author Tim Ferriss
B
Blog
博客园 - 叶小钗
Forbes - Security
Forbes - Security
F
Fortinet All Blogs
Project Zero
Project Zero
K
Kaspersky official blog
Apple Machine Learning Research
Apple Machine Learning Research
L
LINUX DO - 热门话题
The GitHub Blog
The GitHub Blog
H
Hacker News: Front Page
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
PCI Perspectives
PCI Perspectives
The Register - Security
The Register - Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
W
WeLiveSecurity
C
Cyber Attacks, Cyber Crime and Cyber Security
罗磊的独立博客
S
Security @ Cisco Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
P
Proofpoint News Feed
S
SegmentFault 最新的问题
D
Docker
量子位
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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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