Virtual DOM & what is its role in React?

Somnath BaidyaSomnath Baidya
2 min read

First, let’s understand what is DOM: DOM stands for Document Object Model. DOM is a tree-like structure that represents the HTML elements of a webpage. It’s like a blueprint for a webpage. (i) Document- It’s the file where the HTML elements are stored. (ii) Object- Each HTML element/tag is an object. (iii) Model- The model is the hierarchy/sequence of the HTML elements.

A developer accesses this DOM to modify/change the structure, style, and content to update the webpage layout using a programming language like Javascript.

Why Virtual DOM: Direct manipulation of real DOM is slow, inefficient and reduces performance. While direct manipulation, the browser recalculates the layout of the webpage and repaints it. So multiple or small frequent DOM changes may lead to frame drop, delayed interaction or freezing. Virtual DOM resolves these issues.

What is Virtual DOM: Virtual refers to something that has the characteristics of something real but not the real thing itself. So virtual DOM resembles the actual/real DOM but is not the actual DOM itself. We can define virtual DOM like this: Virtual DOM is a lightweight, in-memory representation of the actual(real) DOM.

Role of Virtual DOM in React:

1) Initial Render: When a React component renders, it creates a Virtua DOM tree that mirrors the structure of real/actual DOM.

2) State/Props change: When state or props update, React creates a new Virtual DOM tree.

3) Diffing: Now React compares this newly generated Virtual DOM with the previous Virtual DOM to identify the differences and determine the minimal set of changes needed to avoid unnecessary updates to the real DOM.

4) Reconciliation: Only the differences like updated text and added elements are applied to the actual DOM. This is called reconciliation.

This way react avoids unnecessary rerenders & updates the webpage quickly & efficiently.

0
Subscribe to my newsletter

Read articles from Somnath Baidya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Somnath Baidya
Somnath Baidya

I love creating web applications that address real-world problems and look good. A front end should be simple and useful, not complex and overwhelming. I also love to iterate over new ideas and implement them in real-life applications.