DEV Community

Cover image for What is React Virtual DOM
Puja Kundu
Puja Kundu

Posted on • Updated on

What is React Virtual DOM

What is DOM?

Document Object Model or simply DOM is an Application Programming Interface(API) for HTML and XML documents. When a browser receives an HTML file, it parses it and builds a DOM tree. HTML elements are considered nodes in a DOM tree.

DOM

What is Virtual DOM?

Virtual DOM or VDOM is a virtual representation of the real DOM. It has the same properties as the real DOM but it can not directly change what’s on the screen. React uses virtual DOM. Why? We will get into that now.

Is the real DOM really slow?

What is the first thing that comes to your mind when anybody asks why React uses Virtual DOM? What’s wrong with using the real DOM? - Well, it’s because the real DOM is really slow.

Is it though?

Adding or removing any element from DOM is actually pretty fast. Then why is it called slow?
When we change something in a React component, that change has to be shown on the screen. The process of showing the changes in the UI is slow.

Process

Upon receiving an HTML file, the browser render engine parses it and makes a DOM tree. In the same way, the styles in the CSS file are parsed into CSSOM. Both DOM and CSSOM make a render tree. The render tree has to go through a phase called Layout .
In the Layout phase, the coordinates of the elements of a render tree are found. The coordinates are used to determine the exact position where the elements will be shown on the screen. Lastly, in the Painting phase, the elements are displayed on the screen. When we make any changes in a DOM, the browser has to build the render tree all over again. This repainting process is slow.

How virtual DOM works

state change
Virtual DOM represents the same DOM elements. When we make any change in a react component, every single virtual DOM gets updated. Before updating the VDOM, a snapshot is taken. This snapshot is then compared to the updated virtual DOM to figure out which VDOM object has changed. This process is called diffing. When react knows which object has changed, it updates only those objects in the real dom. These changes in the real DOM cause the screen to change.

Top comments (0)