DEV Community

Cover image for Virtual DOM and Diff algorithm in React
Mst. Poly Khatun
Mst. Poly Khatun

Posted on

Virtual DOM and Diff algorithm in React

Frist We know how to Browser render process

When the browser received an HTML file then the browser this file parses the render engine and creates a DOM tree. DOM tree every HTML element that stays as a node. At the same time, Html came with CSS style This CSS style parses with CSS parser. CSS parser creates CSSOM. This parse CSS and parse HTML creates a render tree. This render tree passed by layout phases and this time the render tree understand that it will be printed In any place. And After all, its does printing and we see them on the display. It is a Browser render process.
Then we any change and any update on the DOM the browser again creates a render tree.

Image description

Virtual DOM

It's also a tree, like a light copy of the DOM. React created 2 DOM trees one DOM tree is before the update tree and another is after the updated tree. Then react can compare in them. In this work, We can real DOM but this is very problematic. Because of this React created separate DOM. Where no problem renders tree repaint. It is a virtual DOM It works very easily. Virtual Dom is not expensive like browser DOM.

Image description

How does Virtual DOM Work

We can think virtual DOM is simple tree. Of which various node is component one by one. when we change any components then at first create a new tree and there are changed components and creates new one's child components. React has two DOM tree representations one is after the changed DOM tree and another is before the changed DOM tree. React compare two DOM trees with a diff algorithm. Then React updated particularly that place on the real DOM.

Diff algorithm

Compare the changes between the old and new virtual DOM, and then update the changed real DOM. While comparing the old and new virtual DOM, change the real DOM node. This process is called diffing. The algorithm that is used for the diffing process is called the diffing algorithm or reconciliation algorithm.

Top comments (0)