What is Virtual DOM in React?

Chief Editor
3 Min Read

Virtual DOM (VDOM):

The Virtual DOM is a lightweight JavaScript object (a virtual representation of the real DOM).


How Virtual DOM Works:

  1. Initial Rendering:
    • When a React application loads, React creates a Virtual DOM representation of the UI based on the initial state.
    • This Virtual DOM is kept in memory.
  2. State Change / UI Update:
    • When the state or props of a component changes, React creates a new Virtual DOM tree.
    • It compares (diffing) the new Virtual DOM with the previous Virtual DOM.
  3. Diffing Algorithm:
    • React calculates the minimum number of changes required (differences between the new Virtual DOM and the old Virtual DOM).
    • It determines which elements in the Real DOM need to be updated.
  4. Efficient DOM Updates:
    • Instead of updating the entire DOM, React updates only the parts that changed.
    • This improves performance and prevents unnecessary re-rendering.

Why Virtual DOM is Efficient:

  • DOM manipulation is slow, but JavaScript operations are fast.
  • React minimizes real DOM manipulations by batching updates.
  • This results in faster UI updates and better performance.

Example Flow:

function App() {
const [count, setCount] = React.useState(0);

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
  1. Initial Render:
    • Virtual DOM created → Real DOM created.
  2. Button Click → setCount() triggers state change.
  3. New Virtual DOM created → Diffed with old Virtual DOM.
  4. Only the h1 part is updated in the Real DOM.

Key Benefits of Virtual DOM:

BenefitDescription
PerformanceReduces real DOM updates, which are costly.
Optimized UpdatesUpdates only the parts of the DOM that changed.
Declarative UIDevelopers focus on describing UI, not managing updates manually.
Cross-platformVirtual DOM is platform-independent, enabling React Native, etc.

React’s Virtual DOM vs Real DOM:

Virtual DOMReal DOM
In-memory representationRepresents the actual DOM elements in the browser.
Fast and efficientSlower due to direct updates and reflows.
Minimizes real DOM updatesEvery change affects the entire DOM.

React’s Rendering Process (Simplified):

  1. Render Phase → Creates a Virtual DOM based on state/props.
  2. Diffing (Reconciliation) → Compares Virtual DOM with the previous version.
  3. Commit Phase → Updates only the necessary parts of the Real DOM.

Key Takeaways:

  • React → Component-based, Declarative, Virtual DOM for performance.
  • Virtual DOM → Improves performance by minimizing real DOM manipulations.
  • Diffing Algorithm → Compares Virtual DOM trees to perform the minimal number of updates.

Let me know if you need help with any other React concepts! 🚀😊

Share This Article
Leave a Comment