DEV Community

Lawaanu Borthakur
Lawaanu Borthakur

Posted on

What is the difference between real DOM and virtual DOM with example?

Let's illustrate the difference between real DOM updates and virtual DOM updates with an example scenario:

Scenario:

Imagine you're building a web application that displays a list of items, and users can add new items to the list by clicking a button.

1. Real DOM Updates:

In this approach, every time a new item is added to the list, the real DOM is directly manipulated to reflect the change.

// HTML
<ul id="item-list"></ul>

// JavaScript
const itemList = document.getElementById('item-list');

function addItem() {
    const newItem = document.createElement('li');
    newItem.textContent = 'New Item';
    itemList.appendChild(newItem);
}
Enter fullscreen mode Exit fullscreen mode

Problem with Real DOM Updates:

  • Each time addItem() is called, the real DOM is modified, triggering reflows and repaints.
  • If there are many items in the list, frequent updates can lead to performance issues, causing the interface to become less responsive.

2. Virtual DOM Updates:

In this approach, instead of directly modifying the real DOM, changes are made to a virtual representation of the DOM first, and then the virtual DOM is compared with the previous state to determine the minimal set of updates needed.

// React.js example
import React, { useState } from 'react';

function ItemList() {
    const [items, setItems] = useState([]);

    function addItem() {
        setItems(prevItems => [...prevItems, 'New Item']);
    }

    return (
        <div>
            <button onClick={addItem}>Add Item</button>
            <ul>
                {items.map((item, index) => (
                    <li key={index}>{item}</li>
                ))}
            </ul>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

How Virtual DOM Addresses the Problems:

  • When addItem() is called, React.js updates the virtual DOM by adding a new item to the list.
  • React.js then calculates the difference (diff) between the new virtual DOM and the previous one.
  • Only the minimal set of changes needed to update the real DOM is applied, avoiding unnecessary reflows and repaints.
  • This approach results in better performance and a smoother user experience, especially in applications with dynamic content or frequent updates.

In summary, the virtual DOM provides an efficient and optimized way to update the real DOM, improving performance and user experience in web applications.

Top comments (0)