DEV Community

Cover image for Understanding React Virtual DOM in Depth: How It Improves Performance
Pratik Nikale
Pratik Nikale

Posted on • Edited on

Understanding React Virtual DOM in Depth: How It Improves Performance

Introduction

React is one of the most popular front-end libraries for building user interfaces, and one of its key performance-enhancing features is the Virtual DOM. You might have heard that React is a single-page application that does not reload the page. Ever wondered how React efficiently updates the UI without reloading the entire page, the Virtual DOM is the answer. In this blog, we'll explore what is a real DOM, Virtual DOM, Structure of DOM, difference between real DOM and Virtual DOM, what makes virtual DOM lightweight, how it works, and why it improves performance in React applications.

What Is the DOM?

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of an HTML or XML document as a tree of objects, where each node corresponds to an element on the page. The DOM allows JavaScript to manipulate elements dynamically, enabling dynamic web pages.

Structure of the DOM

The DOM follows a hierarchical structure, similar to a tree:

  • The root node represents the entire document (<html> tag).
  • Child nodes represent elements such as <head> and <body>.
  • Further branches contain individual elements, attributes, and text nodes.

Example DOM Structure:

Refer to the image, code, and object for a better understanding of the DOM structure.
Example DOM structure

CODE

<html>
  <head>
    <meta></meta>
    <meta></meta>
    <title>Page Title</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
    <p>This is a paragraph.</p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

OBJECT

{
  doctype: "html",
  head: {
    meta: [
      { attributes: {} },
      { attributes: {} }
    ],
    title: "Page Title"
  },
  body: {
    h1: {
      content: "Hello, World!"
    },
    p: {
      content: "This is a paragraph."
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

What Is the Virtual DOM?

The Virtual DOM (VDOM) is a lightweight (I will explain lightweight ahead) JavaScript representation of the actual DOM. Instead of directly manipulating the real DOM, React first updates the Virtual DOM and then efficiently syncs it with the real DOM. This process helps minimize direct manipulations of the DOM, which are usually expensive in terms of performance (we'll dive deeper in this later).

How Is the Virtual DOM Different from the Real DOM?

Real DOM

  • Directly modifies elements
  • Slower due to frequent re-renders
  • Repaints the entire UI on changes
  • Costly, causing performance lag

Virtual DOM

  • Works in memory and updates efficiently
  • Faster due to batched updates
  • Updates only changed elements
  • Lightweight and optimized

What Makes the Virtual DOM Lightweight?

The Virtual DOM (VDOM) is a lightweight JavaScript object that represents the structure of the real DOM. It's essentially a simplified, in-memory copy of the real DOM, designed to be much lighter and faster. Here's what makes it more memory-efficient:

No Layout or Styling Information: The Virtual DOM only contains the basic structure of the UI—essentially, a tree of JavaScript objects representing HTML elements. It does not store style information or layout details (e.g., width, height, padding, etc.).

For example, a <div> in the VDOM may simply be represented as an object with properties like type: 'div', children: [...], and attributes: { className: 'my-div' }. There's no need to hold extra properties for styling or layout.

No Browser Rendering Overhead: The Virtual DOM doesn't interact with the rendering pipeline directly. It's just a plain JavaScript object. No memory is spent managing style recalculations, reflows, or other rendering-specific tasks.

Here how the virtual DOM looks different than real DOM

CODE

<div id="container">
  <p class="text">Hello World</p>
  <button id="myButton">Click Me</button>
</div>
Enter fullscreen mode Exit fullscreen mode

REAL DOM OBJECT

{
  type: 'div',
  id: 'container',
  children: [
    {
      type: 'p',
      className: 'text',
      textContent: 'Hello World',
      style: {
        color: 'black',
        fontSize: '16px'
      },
      children: []
    },
    {
      type: 'button',
      id: 'myButton',
      textContent: 'Click Me',
      style: {
        backgroundColor: 'blue',
        color: 'white',
        fontSize: '14px'
      },
      events: {
        onClick: function() { /* handle click event */ }
      },
      children: []
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

VIRTUAL DOM OBJECT

{
  type: 'div',
  props: { id: 'container' },
  children: [
    {
      type: 'p',
      props: { className: 'text', textContent: 'Hello World' },
      children: []
    },
    {
      type: 'button',
      props: { id: 'myButton', textContent: 'Click Me' },
      children: []
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

How Does the Virtual DOM Work?

Image description
React follows a three-step process to update the UI efficiently:

  1. Rendering the Virtual DOM

    • When a component's state or props change, React creates a new Virtual DOM tree that represents the updated UI.
  2. Diffing Algorithm (Reconciliation)

    • React maintains two versions of the Virtual DOM:
      • Previous Virtual DOM – The representation of the UI before the state or props change.
      • Current Virtual DOM – The newly created Virtual DOM that reflects the updated state or props.
    • React compares the current Virtual DOM with the previous Virtual DOM using a process called reconciliation. It finds the differences between the two trees and determines what has changed.
  3. Updating the Real DOM Efficiently

    • React then applies only the necessary updates to the real DOM, ensuring minimal re-renders and improving performance.

Why Is the Virtual DOM Faster?

1. Batch Updates

Instead of making multiple direct updates to the real DOM, React batches updates to reduce unnecessary reflows and repaints.

2. Efficient Diffing Algorithm

React uses an optimized diffing algorithm to detect changes quickly and apply only the necessary updates to the real DOM.

3. Minimized Direct DOM Manipulation

Since JavaScript operations on objects are faster than direct DOM operations, React processes changes in memory before applying them to the real DOM.

Why Understanding the Virtual DOM Is Necessary for a Good Developer

A deep knowledge of how the Virtual DOM works enables developers to:

  • Optimize rendering performance and prevent unnecessary re-renders.
  • Write more efficient and maintainable React components.
  • Debug and fix performance bottlenecks effectively.
  • Make informed decisions when structuring components and managing state.

By mastering the Virtual DOM, developers can build applications that are not only fast but also scalable and maintainable.

Example: Virtual DOM in Action

Let's look at a simple example where a button click updates the state and re-renders the UI efficiently using the Virtual DOM.

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

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

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Each time the button is clicked, React updates the Virtual DOM, finds the differences, and updates only the relevant part of the real DOM instead of re-rendering the entire page.

Conclusion

The Virtual DOM is a crucial concept in React that enhances performance by optimizing UI updates. By using the diffing algorithm and batching updates, React ensures minimal direct manipulations to the real DOM, leading to a smooth and efficient user experience.

Understanding how the Virtual DOM works can help you write better React applications and optimize rendering performance. Happy coding!

Top comments (0)