React's Virtual DOM

πŸ“š Table of Contents

Introduction

The Virtual DOM(VDOM) is a concept where an virtual representation of a UI is kept in memory and synced with the Real DOM when the updates required.

What is DOM?

Example

document └── <html> β”œβ”€β”€ <head> β”‚ └── <title> β”‚ └── "Page Title" └── <body> └── <div> β”œβ”€β”€ <h1> β”‚ └── "Heading Text" └── <p> └── "Paragraph text"

What is VDOM?

React's Virtual DOM is an abstract representation of a real DOM which stored in in-memory. That is you can assume this like a intermediary state between the react components and real DOM.

How Virtual DOM works?

Usually VDOM works in 3 steps:

  1. Rendering the VDOM
  2. Diffing the VDOM
  3. Updating the Real DOM

Rendering the VDOM

When the application/component state changes, react renders/creates a new Virtual DOM representing the updates happened recently in the application state.

Diffing the Virtual DOM

In this step, React compares the recently/newly created Virtual DOM tree with the previous one using a process called Reconciliation. This process identifies the differences between the two trees. To identify the difference, React uses the Diffing Algorithm where it compares each node of both trees to find the changes.

Updating the Real DOM

Example

Let's consider a Simple Component which shows a Hello Message and a description

const MyComponent = () => { return ( <div> <h1>Hello</h1> <p>Welcome to my site.</p> </div> ) }
VDOM (Old) └── <div> β”œβ”€β”€ <h1> β”‚ └── "Hello" └── <p> └── "Welcome to my site."
VDOM (New) └── <div> β”œβ”€β”€ <h1> β”‚ └── "Hello" └── <p> └── "Welcome to my updated site."
Comparing: <p> "Welcome to my site." ⟢ <p> "Welcome to my updated site." β†’ Text inside <p> has changed β†’ <h1> remains unchanged
- React identifies that <p> content as changed.
- No need to update <div> & <h1> again
Real DOM Before └── <div> β”œβ”€β”€ <h1> Hello </h1> └── <p> Welcome to my site. </p> ⟢ Update only <p>: Real DOM After └── <div> β”œβ”€β”€ <h1> Hello </h1> └── <p> Welcome to my updated site. </p>

Key benefits of VDOM