Skip to main content

What is Virtual DOM?

Definition

Virtual DOM is a lightweight copy of the real DOM tree, that exists in memory (in JavaScript) and is used by React to efficiently update the interface.


How it works (step by step)

  1. You describe the interface as JSX:
javascript
<div> <h1>Hello</h1> <button>Click</button> </div>
  1. React creates an object representation of this tree in memory - the Virtual DOM:
javascript
{ type: "div", props: { children: [ { type: "h1", props: { children: "Hello" } }, { type: "button", props: { children: "Click" } } ] } }
  1. When data (state, props) changes - React creates a new Virtual DOM tree.
  2. Then React compares the new and the previous tree (this process is called diffing).
  3. After that React finds the differences and changes only the parts of the real DOM that actually changed.

Without Virtual DOM

If React worked directly with the real DOM:

  • any data change → the whole node is redrawn;
  • DOM operations are slow, especially on large trees;
  • frequent renders → performance drops.

With Virtual DOM

React works in memory:

  • it counts changes at the level of JS objects;
  • it updates only the needed elements in the real DOM;
  • it makes the process much faster and more optimal.

Example

Before:

javascript
<p>Likes: 4</p>

After:

javascript
<p>Likes: 5</p>

React:

  1. Compares two Virtual DOM trees.
  2. Sees that only the number 4 → 5 changed.
  3. Changes only the text inside <p>, instead of redrawing the whole <body>.

Visual analogy

Imagine the Virtual DOM as a draft:

  • You first make changes in the draft (in memory),
  • You compare it with the original,
  • And carefully apply only the needed edits to the "clean copy" (the real DOM).

Diffing and Reconciliation

React uses the reconciliation algorithm:

  • it compares the old and new Virtual DOM trees;
  • if nodes are the same → it reuses them;
  • if they differ → it updates or replaces them in the real DOM;
  • it does this very fast thanks to keys (key) and heuristics.

Advantages of Virtual DOM

  • Increases performance (fewer operations on the real DOM)
  • Simplifies working with the UI (you do not need to update elements manually)
  • Lets React be declarative - you just describe what should be, not how to draw it
  • Provides cross-platform support (the same mechanism is used in React Native)

Summary

WhatDescription
DOMThe real tree of elements in the browser
Virtual DOMA lightweight copy of the DOM in memory
DiffingComparison of the old and new Virtual DOM
ReconciliationThe process of updating the real DOM based on the comparison results

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.