1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Virtual Dom
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
10Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Virtual Dom

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
10Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Virtual DOM

Overview

The Virtual DOM (VDOM) is the core engine behind React's blazing-fast performance. In traditional web development, whenever data changed, you had to manually update the real browser DOM. The real DOM is essentially a massive, heavy tree structure. Modifying it forces the browser to recalculate CSS, layout, and repaint the screen—an incredibly slow and expensive process.

React solves this by keeping a lightweight, in-memory representation of the DOM (the Virtual DOM) entirely in JavaScript. When the state of your application changes, React doesn't immediately touch the real DOM. Instead, it creates a completely new Virtual DOM tree representing what the UI should look like.

React then runs a 'Diffing Algorithm' (called Reconciliation) to compare the New Virtual DOM against the Old Virtual DOM. It calculates the exact, minimal set of changes required (e.g., 'only this one text node changed'). Finally, it 'commits' those specific changes to the real browser DOM in one single batch. This minimizes expensive browser repaints and keeps complex apps running smoothly at 60 frames per second.

Syntax

The Diffing Concept (Mental Model)
javascript
// 1. Initial State (Old VDOM)
const oldVdom = {
  type: 'div',
  props: { className: 'card' },
  children: 'Status: Pending'
};

// 2. Data updates. React generates a New VDOM
const newVdom = {
  type: 'div',
  props: { className: 'card' },
  children: 'Status: Complete' // ONLY this string changed
};

// 3. React compares them (Reconciliation), sees only the text changed,
// and updates just the innerText of that specific node in the Real DOM.

Common Pitfalls

  • Assuming the Virtual DOM is faster than vanilla JS: A common misconception is that React is faster than pure vanilla JavaScript. It is not. Nothing is faster than a perfectly written, targeted vanilla JS DOM update. The Virtual DOM's true value is that it provides the performance of perfectly optimized vanilla JS while allowing developers to write highly maintainable, declarative code.

Interview Questions

Explain the Reconciliation process in React.

Reconciliation is React's 'diffing' algorithm. When component state changes, React generates a new Virtual DOM tree. It compares this new tree against the previous Virtual DOM tree to find exactly what changed. Once it identifies the differences, it updates only those specific nodes in the real browser DOM.

Why is updating the real DOM considered slow?

The DOM itself is just a tree of objects, which is fast to update. However, every time you alter the DOM, the browser has to recalculate CSS rules, figure out the spatial layout of elements on the screen, and repaint the pixels. These layout and paint phases are highly CPU-intensive and slow.

Real-World Example

Real-Time Stock Market Dashboard: In a stock dashboard with 100 prices updating every second, aggressively destroying and recreating the real DOM would freeze the browser. React's Virtual DOM batches these micro-updates, ensuring only the exact numbers that changed are repainted on the screen.

example
javascript
function StockTicker({ stocks }) {
  return (
    <ul>
      {stocks.map(stock => (
        <li key={stock.ticker}>
          {stock.ticker}: ${stock.price}
        </li>
      ))}
    </ul>
  );
}
// If only Apple's (AAPL) stock price changes from 150 to 151,
// React's Virtual DOM diffs the lists, realizes 99 stocks are identical,
// and ONLY updates the single text node for AAPL in the real browser DOM.

Check Your Knowledge

Test your understanding of Virtual DOM with these quick questions.

Question 1

What is the process of comparing the old Virtual DOM with the new Virtual DOM called?

Question 2

Is the Virtual DOM a feature provided by the browser?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Virtual DOM

Overview

The Virtual DOM (VDOM) is the core engine behind React's blazing-fast performance. In traditional web development, whenever data changed, you had to manually update the real browser DOM. The real DOM is essentially a massive, heavy tree structure. Modifying it forces the browser to recalculate CSS, layout, and repaint the screen—an incredibly slow and expensive process.

React solves this by keeping a lightweight, in-memory representation of the DOM (the Virtual DOM) entirely in JavaScript. When the state of your application changes, React doesn't immediately touch the real DOM. Instead, it creates a completely new Virtual DOM tree representing what the UI should look like.

React then runs a 'Diffing Algorithm' (called Reconciliation) to compare the New Virtual DOM against the Old Virtual DOM. It calculates the exact, minimal set of changes required (e.g., 'only this one text node changed'). Finally, it 'commits' those specific changes to the real browser DOM in one single batch. This minimizes expensive browser repaints and keeps complex apps running smoothly at 60 frames per second.

Syntax

The Diffing Concept (Mental Model)
javascript
// 1. Initial State (Old VDOM)
const oldVdom = {
  type: 'div',
  props: { className: 'card' },
  children: 'Status: Pending'
};

// 2. Data updates. React generates a New VDOM
const newVdom = {
  type: 'div',
  props: { className: 'card' },
  children: 'Status: Complete' // ONLY this string changed
};

// 3. React compares them (Reconciliation), sees only the text changed,
// and updates just the innerText of that specific node in the Real DOM.

Common Pitfalls

  • Assuming the Virtual DOM is faster than vanilla JS: A common misconception is that React is faster than pure vanilla JavaScript. It is not. Nothing is faster than a perfectly written, targeted vanilla JS DOM update. The Virtual DOM's true value is that it provides the performance of perfectly optimized vanilla JS while allowing developers to write highly maintainable, declarative code.

Interview Questions

Explain the Reconciliation process in React.

Reconciliation is React's 'diffing' algorithm. When component state changes, React generates a new Virtual DOM tree. It compares this new tree against the previous Virtual DOM tree to find exactly what changed. Once it identifies the differences, it updates only those specific nodes in the real browser DOM.

Why is updating the real DOM considered slow?

The DOM itself is just a tree of objects, which is fast to update. However, every time you alter the DOM, the browser has to recalculate CSS rules, figure out the spatial layout of elements on the screen, and repaint the pixels. These layout and paint phases are highly CPU-intensive and slow.

Real-World Example

Real-Time Stock Market Dashboard: In a stock dashboard with 100 prices updating every second, aggressively destroying and recreating the real DOM would freeze the browser. React's Virtual DOM batches these micro-updates, ensuring only the exact numbers that changed are repainted on the screen.

example
javascript
function StockTicker({ stocks }) {
  return (
    <ul>
      {stocks.map(stock => (
        <li key={stock.ticker}>
          {stock.ticker}: ${stock.price}
        </li>
      ))}
    </ul>
  );
}
// If only Apple's (AAPL) stock price changes from 150 to 151,
// React's Virtual DOM diffs the lists, realizes 99 stocks are identical,
// and ONLY updates the single text node for AAPL in the real browser DOM.

Check Your Knowledge

Test your understanding of Virtual DOM with these quick questions.

Question 1

What is the process of comparing the old Virtual DOM with the new Virtual DOM called?

Question 2

Is the Virtual DOM a feature provided by the browser?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A