DEV Community

Cover image for Virtual DOM in React
Mahalakshmi C
Mahalakshmi C

Posted on

Virtual DOM in React

The Virtual DOM (Document Object Model) is one of the important concepts in React. It helps React update the user interface efficiently.

What is Virtual DOM?

The Virtual DOM is a lightweight JavaScript representation of the actual DOM.

The actual DOM represents the elements on a webpage, such as headings, buttons, paragraphs, images, and forms.

React does not directly update the entire actual DOM whenever something changes. Instead, it uses the Virtual DOM to find out what has changed.

How Does Virtual DOM Work?

The basic process is:

  1. React creates a Virtual DOM that represents the UI.
  2. When the data or state changes, React creates a new Virtual DOM.
  3. React compares the new Virtual DOM with the previous Virtual DOM.
  4. It identifies the changed elements.
  5. React updates only those changed parts in the actual DOM.

This comparison process is commonly referred to as reconciliation.

Example

Suppose the UI initially displays:

Hello
Count: 1
Enter fullscreen mode Exit fullscreen mode

After the count changes:

Hello
Count: 2
Enter fullscreen mode Exit fullscreen mode

React does not need to recreate the entire page. It identifies that only the count has changed and updates that part of the UI.

Simple Flow

Initial UI
    ↓
Virtual DOM
    ↓
State changes
    ↓
New Virtual DOM
    ↓
Compare old and new Virtual DOM
    ↓
Find changes
    ↓
Update required part of Actual DOM
Enter fullscreen mode Exit fullscreen mode

Virtual DOM vs Actual DOM

Virtual DOM Actual DOM
JavaScript representation of the UI Represents the actual webpage
Lightweight More expensive to manipulate
Managed by React Managed by the browser
Used to determine UI changes Displays the UI

Conclusion

The Virtual DOM helps React manage UI updates efficiently. Instead of unnecessarily changing the entire webpage, React determines which parts need to change and updates those parts in the actual DOM.

Top comments (0)