In this blog, we’ll talk about what Virtual DOM is and how it works in React. If you are a React Developer, you might not even know how React components turn into the elements on the Web page.
As we all know that Document object model works on a tree. Each node of that tree represents the Elements. In Real DOM when we change HTML it renders the whole tree. But in Virtual DOM it just updates the specific node of the tree.
When React builds its tree of components, it makes its own DOM, called the virtual DOM, in memory. The virtual DOM is a copy of the browser’s DOM that is kept in memory. This virtual DOM is what React uses to change the browser’s DOM when it the change occurs to the element. This makes sure that your app works quickly and responds to what users input.
Let me explain what happens when you update a component in React.
The virtual DOM is updated first. Then React compares the virtual DOM to the previous version of the virtual DOM, and determines which elements have changed. This method is called Diffing Algorithm. The changed elements and only those elements are updated in the browser DOM. Changes on the browser DOM cause the displayed web page to change.
Here we breaken down into the following steps.
- Step 1: The virtual DOM is updated.
- Step 2: The virtual DOM is compared to the previous version of the virtual DOM and checks which Node elements have changed.
- Step 3: The changed Node elements are updated in the browser DOM tree.
- Step 4: The displayed webpage updates to match the browser DOM.