How React Implements the Virtual DOM

This article explains how React implements the Virtual DOM to optimize web performance. We will explore the core concept of the Virtual DOM, the step-by-step process React uses to update the user interface, and how the reconciliation algorithm minimizes expensive updates to the real DOM.

What is the Virtual DOM?

The Virtual DOM (VDOM) is a programming concept where a lightweight, virtual representation of the user interface is kept in memory and synced with the “real” DOM. In React, this representation consists of plain JavaScript objects that mimic the structure of actual DOM elements.

The Step-by-Step Implementation Process

React implements the Virtual DOM through a multi-step pipeline whenever a user interacts with an application:

1. Creating the Virtual DOM Tree

When a component renders, React creates a tree of Virtual DOM nodes. Code written in JSX is compiled down to React.createElement() calls, which return simple JavaScript objects. For example, <div>Hello</div> becomes:

{
  type: 'div',
  props: {
    children: 'Hello'
  }
}

2. Initial Rendering

During the initial load, React renders the entire Virtual DOM tree and translates it into actual HTML nodes, inserting them into the real browser DOM.

3. Detecting State and Prop Changes

When a component’s state or props change, React triggers a re-render. Instead of touching the real DOM immediately, React generates an entirely new Virtual DOM tree representing the updated state of the UI.

4. Diffing (Reconciliation)

React compares the newly created Virtual DOM tree with the previous Virtual DOM tree (which was saved in memory before the update). This comparison process is governed by a highly optimized heuristic algorithm called Reconciliation.

During reconciliation, React applies two main rules to keep the process fast: * Different Element Types: If two elements have different types (e.g., swapping a <div> for a <span>), React will tear down the old tree and build the new one from scratch. * Keys for Lists: React uses the key prop to identify which child elements have changed, been added, or been removed in lists, preventing unnecessary re-renders.

5. Patching the Real DOM

Once React identifies the exact differences (the “diff”) between the old and new Virtual DOMs, it batches the changes. It then updates only the specific elements in the real browser DOM that actually changed. This selective updating is significantly faster than reloading the entire webpage or re-rendering whole sections of the real DOM.