Virtual DOM

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

Virtual DOM

The Virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.

Why does the Virtual DOM exist?

Manipulating the real DOM (Document Object Model) is slow. The DOM is represented as a tree structure, and whenever it is updated, the browser has to recalculate CSS, do layout, and repaint the web page. If you are updating the DOM frequently (e.g., rendering a list of thousands of items, or animating an element), these operations become a massive performance bottleneck.

React introduced the Virtual DOM to abstract this manual DOM manipulation away from the developer and to optimize updates.

How it Works

  1. Initial Render: When your React app starts, React creates a Virtual DOM tree that mirrors the structure of your React components. This Virtual DOM is just a lightweight JavaScript object. React then takes this Virtual DOM and renders it into the real DOM.
  2. State Change: When a state or prop changes in your app, React creates a completely new Virtual DOM tree representing the new desired state of the UI.
  3. Diffing: React compares the new Virtual DOM tree with the previous Virtual DOM tree (the “diffing” process). It figures out exactly what changed.
  4. Patching (Commit): Once React knows the exact differences, it updates the real DOM in a highly optimized batch operation, only touching the nodes that actually need to change.

The Virtual DOM is just JavaScript Objects

It’s important to realize there is no magic to the Virtual DOM. It is literally just a tree of plain JavaScript objects.

When you write JSX:

const element = <h1 className="greeting">Hello, world!</h1>;

Babel compiles it to:

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

Which returns a plain JavaScript object (a Virtual DOM node):

// A simplified view of a Virtual DOM object
{
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
}

Because updating and comparing plain JavaScript objects in memory is incredibly fast (orders of magnitude faster than touching the browser’s DOM), React can calculate UI updates with minimal performance overhead.

Interview Questions

Q: Why is the Virtual DOM faster than manipulating the real DOM directly?
A: The real DOM is incredibly slow because mutating it triggers browser repaints, reflows, and layout calculations. The Virtual DOM is just a lightweight JavaScript object residing in memory. React rapidly calculates all changes in this JS object first, and then batches the updates into a single, optimized set of real DOM mutations.