React  

What is Virtual DOM in React?

The Real DOM is the actual structure of elements in your browser (the webpage).

Updating the Real DOM directly is slow because every small change (like changing text or color) can trigger a re-render of the entire page or parts of it.

To fix this, React uses the Virtual DOM :

  • It’s a copy of the real DOM kept in memory.

  • React updates this virtual copy first.

  • Then it compares (or “diffs”) the old and new virtual DOM to find what actually changed .

  • Finally, React updates only the necessary parts of the real DOM, not the whole page.

How does it work?

  1. Render Phase: You write a React component (JSX) -> React creates a Virtual DOM tree (a JavaScript object that represents UI structure).

  2. Update Phase: When state or props change, React creates a new Virtual DOM .

  3. Diffing Algorithm: React compares the new VDOM to the previous one to find minimal changes (called reconciliation ).

  4. Commit Phase: React updates only those changed elements in the Real DOM .

Example

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

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

When you click the button:

  • React builds a new virtual DOM with the updated count.

  • It compares the new and old VDOM trees.

  • It sees that only the <h1> text changed.

  • It updates just that text in the real DOM.

Rikam Palkar React VDOM

Benefit

  • Faster UI updates (compared to manual DOM manipulation).