JavaScript and React course Β· Module 1: React Basics

Virtual DOM and its advantages

4 min read Β·
In this lesson6

One of React's most innovative features is the concept of Virtual DOM (Document Object Model). To understand its significance, we first need to understand the problem it solves.

The problem with traditional DOM

Imagine the browser's DOM as a huge star map, where every star, planet, and space station must be precisely placed. Every change to this map has a cost: the browser has to recalculate the positions of the objects the change affects.

In the traditional approach, when a user performs an action (e.g., clicks a button), it is up to you to:

  1. Find all the DOM elements affected by the change
  2. Update each of them by hand - or, for convenience, rebuild the whole section of the page (e.g., with innerHTML)

After every change the browser recalculates styles and layout and repaints the changed part of the page. When you rebuild a whole section, it does this for all of its elements, even if only one of them changed.

It's like redesigning the entire spaceship when you just want to change the color of one button on the control panel!

How Virtual DOM works

React introduced a revolutionary approach:

  1. The user performs an action
  2. React creates a new Virtual DOM (a lightweight JavaScript copy of the real DOM)
  3. React compares the previous Virtual DOM with the new one (the "diffing" algorithm)
  4. React updates only those elements of the real DOM that actually changed

It's like having a holographic mockup of the spaceship, where you plan changes and test them before applying them to the real ship. This process is incredibly efficient, especially in complex applications where many elements can change simultaneously.

Virtual DOM in action - example

Consider a simple example: we have a to-do list, and a user just marked one task as completed.

In the traditional approach:

  1. Either you find and update the right list item yourself - and you have to remember every such place in your code
  2. Or you rebuild the whole list (e.g., with innerHTML) - simpler, but the browser then processes every item in the list

With React and Virtual DOM:

  1. React creates a new version of the Virtual DOM with the updated task state
  2. Compares it with the previous version
  3. Finds only one changed element (the task marked as completed)
  4. Updates only that specific element in the real DOM

Virtual DOM implementation details

Virtual DOM operates on several levels:

  1. Element representation - Each JSX element is transformed into a lightweight JavaScript object representing a DOM node
  2. Reconciliation - The process of comparing two Virtual DOM trees and calculating the minimal set of operations needed to update the real DOM
  3. Batching - React groups multiple updates into a single session to minimize the number of operations on the real DOM
// This JSX code
<div className="task-list">
  <Task completed={true} name="Task 1" />
  <Task completed={false} name="Task 2" />
</div>

// Is transformed into a structure similar to this (simplified)
{
  type: 'div',
  props: {
    className: 'task-list',
    children: [
      {
        type: Task,
        props: { completed: true, name: 'Task 1' }
      },
      {
        type: Task,
        props: { completed: false, name: 'Task 2' }
      }
    ]
  }
}

Advantages of Virtual DOM

The advantages of this approach are enormous:

  1. Performance - especially in complex applications where the traditional approach could cause noticeable delays
  2. DOM abstraction - developers can focus on application logic rather than DOM manipulation details
  3. Predictability - easier to track state changes and debug problems
  4. Ease of testing - components can be tested in isolation
  5. Cross-platform - since Virtual DOM is a regular JavaScript object, the same concept can be used on different platforms (Web, Mobile with React Native)

Fiber - the new generation of Virtual DOM

Since React 16, a new implementation of the reconciliation algorithm called Fiber was introduced. This architecture enables:

  • Interruptible updates - long rendering operations can be divided into smaller parts
  • Update prioritization - some updates (e.g., animations) can have higher priority
  • Better error handling
  • Better support for Concurrent Mode

This evolution of Virtual DOM shows how React continually develops its key technologies to meet the challenges of modern web applications.

Code for this lesson: App.jsx
import React from 'react';

// Component demonstrating traditional DOM
function TraditionalDOMDemo() {
  const [updates, setUpdates] = React.useState(0);
  const [isAnimating, setIsAnimating] = React.useState(false);

  const simulateTraditionalUpdate = () => {
    setIsAnimating(true);
    setUpdates(prev => prev + 1);

    setTimeout(() => {
      setIsAnimating(false);
    }, 1000);
  };

  return (
    <div style={{
      backgroundColor: '#ffebee',
      padding: '20px',
      borderRadius: '8px',
      border: '2px solid #f44336',
      margin: '15px 0'
    }}>
      <h3 style={{ color: '#c62828', marginBottom: '15px' }}>
        Traditional DOM (Slow)
      </h3>

      <div style={{
        display: 'flex',
        alignItems: 'center',
        marginBottom: '15px',
        gap: '15px'
      }}>
        <button
          onClick={simulateTraditionalUpdate}
          disabled={isAnimating}
          style={{
            padding: '10px 20px',
            backgroundColor: isAnimating ? '#ccc' : '#f44336',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: isAnimating ? 'not-allowed' : 'pointer'
          }}
        >
          {isAnimating ? 'Updating...' : 'Update DOM'}
        </button>

        <div style={{
          padding: '8px 15px',
          backgroundColor: 'white',
          borderRadius: '4px',
          border: '1px solid #ccc'
        }}>
          Updates: {updates}
        </div>
      </div>

      <div style={{
        backgroundColor: 'white',
        padding: '15px',
        borderRadius: '4px',
        opacity: isAnimating ? 0.5 : 1,
        transition: 'opacity 1s'
      }}>
        <h4>Traditional update steps:</h4>
        <ol style={{ color: '#666' }}>
          <li>Find all elements to change</li>
          <li>Change each element individually</li>
          <li>Recalculate styles and layout (reflow)</li>
          <li>Repaint the changed part of the page (repaint)</li>
        </ol>
        {isAnimating && (
          <div style={{
            color: '#f44336',
            fontStyle: 'italic',
            marginTop: '10px'
          }}>
            ⏳ Updating... This can take a while for large pages!
          </div>
        )}
      </div>
    </div>
  );
}

// Component demonstrating Virtual DOM
function VirtualDOMDemo() {
  const [updates, setUpdates] = React.useState(0);
  const [isProcessing, setIsProcessing] = React.useState(false);
  const [virtualChanges, setVirtualChanges] = React.useState([]);

  const simulateVirtualDOMUpdate = () => {
    setIsProcessing(true);
    setVirtualChanges(['Creating Virtual DOM...']);

    setTimeout(() => {
      setVirtualChanges(['Creating Virtual DOM...', 'Comparing with previous version...']);
    }, 300);

    setTimeout(() => {
      setVirtualChanges([
        'Creating Virtual DOM...',
        'Comparing with previous version...',
        'Found 1 change to update'
      ]);
    }, 600);

    setTimeout(() => {
      setVirtualChanges([
        'Creating Virtual DOM...',
        'Comparing with previous version...',
        'Found 1 change to update',
        'Updating only necessary elements'
      ]);
      setUpdates(prev => prev + 1);
      setIsProcessing(false);
    }, 900);

    setTimeout(() => {
      setVirtualChanges([]);
    }, 2000);
  };

  return (
    <div style={{
      backgroundColor: '#e8f5e8',
      padding: '20px',
      borderRadius: '8px',
      border: '2px solid #4caf50',
      margin: '15px 0'
    }}>
      <h3 style={{ color: '#2e7d32', marginBottom: '15px' }}>
        React Virtual DOM (Fast)
      </h3>

      <div style={{
        display: 'flex',
        alignItems: 'center',
        marginBottom: '15px',
        gap: '15px'
      }}>
        <button
          onClick={simulateVirtualDOMUpdate}
          disabled={isProcessing}
          style={{
            padding: '10px 20px',
            backgroundColor: isProcessing ? '#ccc' : '#4caf50',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: isProcessing ? 'not-allowed' : 'pointer'
          }}
        >
          {isProcessing ? 'Processing...' : 'Update Virtual DOM'}
        </button>

        <div style={{
          padding: '8px 15px',
          backgroundColor: 'white',
          borderRadius: '4px',
          border: '1px solid #ccc'
        }}>
          Updates: {updates}
        </div>
      </div>

      <div style={{
        backgroundColor: 'white',
        padding: '15px',
        borderRadius: '4px'
      }}>
        <h4>Virtual DOM Process:</h4>
        <ul style={{ color: '#666', minHeight: '100px' }}>
          {virtualChanges.map((change, index) => (
            <li key={index} style={{
              marginBottom: '5px',
              opacity: 0,
              animation: 'fadeIn 0.5s forwards',
              animationDelay: `${index * 0.2}s`
            }}>
              {change}
            </li>
          ))}
          {!isProcessing && virtualChanges.length === 0 && (
            <li style={{ color: '#999', fontStyle: 'italic' }}>
              Click the button to see the Virtual DOM process in action
            </li>
          )}
        </ul>
      </div>

      <style>
        {`
          @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
          }
        `}
      </style>
    </div>
  );
}

// Component demonstrating performance differences
function PerformanceDifference() {
  const [itemCount, setItemCount] = React.useState(100);
  const [items, setItems] = React.useState([]);

  React.useEffect(() => {
    const newItems = Array.from({ length: itemCount }, (_, i) => ({
      id: i,
      name: `Element ${i + 1}`,
      value: Math.floor(Math.random() * 100)
    }));
    setItems(newItems);
  }, [itemCount]);

  const updateAllItems = () => {
    setItems(prevItems =>
      prevItems.map(item => ({
        ...item,
        value: Math.floor(Math.random() * 100)
      }))
    );
  };

  return (
    <div style={{
      backgroundColor: '#f3e5f5',
      padding: '20px',
      borderRadius: '8px',
      border: '2px solid #9c27b0',
      margin: '15px 0'
    }}>
      <h3 style={{ color: '#7b1fa2', marginBottom: '15px' }}>
        Virtual DOM Performance Demonstration
      </h3>

      <div style={{
        display: 'flex',
        gap: '15px',
        marginBottom: '15px',
        flexWrap: 'wrap',
        alignItems: 'center'
      }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          Number of elements:
          <input
            type="range"
            min="50"
            max="1000"
            step="50"
            value={itemCount}
            onChange={(e) => setItemCount(Number(e.target.value))}
            style={{ width: '150px' }}
          />
          <span style={{ minWidth: '60px' }}>{itemCount}</span>
        </label>

        <button
          onClick={updateAllItems}
          style={{
            padding: '10px 20px',
            backgroundColor: '#9c27b0',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer'
          }}
        >
          Update All
        </button>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(120px, 1fr))',
        gap: '8px',
        maxHeight: '200px',
        overflow: 'auto',
        backgroundColor: 'white',
        padding: '15px',
        borderRadius: '4px'
      }}>
        {items.map(item => (
          <div
            key={item.id}
            style={{
              padding: '8px',
              backgroundColor: `hsl(${item.value * 3.6}, 70%, 90%)`,
              borderRadius: '4px',
              textAlign: 'center',
              fontSize: '12px',
              transition: 'background-color 0.3s'
            }}
          >
            <div style={{ fontWeight: 'bold' }}>{item.name}</div>
            <div>{item.value}</div>
          </div>
        ))}
      </div>

      <div style={{
        marginTop: '15px',
        padding: '10px',
        backgroundColor: 'white',
        borderRadius: '4px',
        fontSize: '14px',
        color: '#666'
      }}>
        <strong>Note:</strong> Even when updating {itemCount} elements,
        React, thanks to Virtual DOM, smoothly processes changes and updates only
        those elements that actually changed!
      </div>
    </div>
  );
}

// Component with interactive process visualization
function VirtualDOMVisualization() {
  const [step, setStep] = React.useState(0);
  const steps = [
    { title: "Initial State", desc: "We have an existing Virtual DOM" },
    { title: "State Change", desc: "The user performs an action (e.g. clicks a button)" },
    { title: "New Virtual DOM", desc: "React creates a new Virtual DOM" },
    { title: "Diff Algorithm", desc: "React compares the old and new Virtual DOM" },
    { title: "Minimal Changes", desc: "React identifies the minimal set of changes" },
    { title: "DOM Update", desc: "Only the necessary elements are updated" }
  ];

  const nextStep = () => {
    setStep(prev => (prev + 1) % steps.length);
  };

  const resetSteps = () => {
    setStep(0);
  };

  return (
    <div style={{
      backgroundColor: '#fff3e0',
      padding: '20px',
      borderRadius: '8px',
      border: '2px solid #ff9800',
      margin: '15px 0'
    }}>
      <h3 style={{ color: '#f57c00', marginBottom: '15px' }}>
        Step By Step: How Virtual DOM Works
      </h3>

      <div style={{
        display: 'flex',
        gap: '10px',
        marginBottom: '20px'
      }}>
        <button onClick={nextStep} style={{
          padding: '10px 20px',
          backgroundColor: '#ff9800',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: 'pointer'
        }}>
          Next Step
        </button>

        <button onClick={resetSteps} style={{
          padding: '10px 20px',
          backgroundColor: '#666',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: 'pointer'
        }}>
          Reset
        </button>
      </div>

      <div style={{
        backgroundColor: 'white',
        padding: '20px',
        borderRadius: '8px',
        minHeight: '120px'
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          marginBottom: '15px'
        }}>
          <div style={{
            width: '40px',
            height: '40px',
            backgroundColor: '#ff9800',
            color: 'white',
            borderRadius: '50%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontWeight: 'bold',
            marginRight: '15px'
          }}>
            {step + 1}
          </div>
          <h4 style={{ margin: 0, color: '#333' }}>
            {steps[step].title}
          </h4>
        </div>

        <p style={{ color: '#666', fontSize: '16px', lineHeight: '1.5' }}>
          {steps[step].desc}
        </p>

        <div style={{
          marginTop: '15px',
          display: 'flex',
          gap: '5px'
        }}>
          {steps.map((_, index) => (
            <div
              key={index}
              style={{
                width: '12px',
                height: '12px',
                borderRadius: '50%',
                backgroundColor: index <= step ? '#ff9800' : '#ddd',
                transition: 'background-color 0.3s'
              }}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

export default function App() {
  return (
    <div style={{
      fontFamily: 'Arial, sans-serif',
      maxWidth: '900px',
      margin: '0 auto',
      padding: '20px'
    }}>
      <header style={{
        textAlign: 'center',
        marginBottom: '30px',
        padding: '25px',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        color: 'white',
        borderRadius: '12px'
      }}>
        <h1 style={{ margin: '0 0 10px 0', fontSize: '2.2rem' }}>
          Virtual DOM and its benefits
        </h1>
        <p style={{ margin: 0, fontSize: '1rem', opacity: 0.9 }}>
          Discover the secret of React's performance and understand why Virtual DOM
          is a true revolution in the world of front-end development
        </p>
      </header>

      <section style={{ marginBottom: '30px' }}>
        <h2 style={{
          color: '#333',
          borderBottom: '2px solid #667eea',
          paddingBottom: '10px',
          marginBottom: '20px'
        }}>
          Traditional DOM vs Virtual DOM
        </h2>

        <TraditionalDOMDemo />
        <VirtualDOMDemo />
      </section>

      <VirtualDOMVisualization />
      <PerformanceDifference />

      <div style={{
        backgroundColor: '#e3f2fd',
        padding: '25px',
        borderRadius: '12px',
        marginTop: '30px'
      }}>
        <h3 style={{ color: '#1976d2', textAlign: 'center', marginBottom: '20px' }}>
          Key Virtual DOM benefits
        </h3>

        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
          gap: '20px'
        }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '40px', marginBottom: '10px' }}>β†―</div>
            <h4 style={{ color: '#1976d2' }}>Performance</h4>
            <p style={{ margin: 0, color: '#666' }}>
              Minimal DOM updates = faster applications
            </p>
          </div>

          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '40px', marginBottom: '10px' }}>β—†</div>
            <h4 style={{ color: '#1976d2' }}>Predictability</h4>
            <p style={{ margin: 0, color: '#666' }}>
              Easier change tracking and debugging
            </p>
          </div>

          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '40px', marginBottom: '10px' }}>β—†</div>
            <h4 style={{ color: '#1976d2' }}>Testability</h4>
            <p style={{ margin: 0, color: '#666' }}>
              Components can be tested in isolation
            </p>
          </div>

          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: '40px', marginBottom: '10px' }}>●</div>
            <h4 style={{ color: '#1976d2' }}>Cross-platform</h4>
            <p style={{ margin: 0, color: '#666' }}>
              The same concept works everywhere
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is Virtual DOM in React?

  2. 2. What are components in React?

  3. 3. What is the main benefit of Virtual DOM in React?

  4. 4. What does the diffing (reconciliation) algorithm in React do?

Hands-on tasks in the game

  • Click in order

    Arrange the Virtual DOM process in order:

  1. QuestionHow does Virtual DOM work?
  2. QuestionComponents - the building blocks of applications
  3. Click in orderSorting: Virtual DOM flow
  4. QuestionBenefits of Virtual DOM
  5. QuestionDiffing algorithm in Virtual DOM

Useful articles