What is Virtual Dom in React?
Normally, whenever a user requests a webpage, the browser receives an HTML document for that page from the server. The browser then constructs a logical, tree-like structure from the HTML to show the user the requested page in the client.
How re-rendering impacts performance in real Dom?
- As seen in the GIF Above, the document DOM elements are rebuilt and repainted on each update. The text input in the UI also loses its state due to this re-rendering.
How React implements the virtual DOM?
To understand the virtual DOM strategy, we need to understand the two major phases that are involved, rendering and reconciliation.
When we render an application user interface, React creates a virtual DOM tree representing that UI and stores it in memory. On the next update, or in other words, when the data that renders the app changes, React will automatically create a new virtual DOM tree for the update.
The image on the left is the initial render. As the
Time
changes, react creates a new tree with the updated node, as seen on the right side.Remember, the virtual DOM is just an object representing the UI, so nothing gets drawn on the screen.
After React creates the new virtual DOM tree, it compares it to the previous snapshot using a diffing algorithm called reconciliation to figure out what changes are necessary.
After the reconciliation process, React uses a renderer library like ReactDOM, which takes the differ information to update the rendered app. This library ensures that the actual DOM only receives and repaints the updated node or nodes.
As seen in the image above, only the node whose data changes gets repainted in the actual DOM. The GIF below further proves this statement.
Conclusion
React uses the virtual DOM as a strategy to compute minimal DOM operations when re-rendering the UI. It is not in rivalry with or faster than the real DOM.
The virtual DOM provides a mechanism that abstracts manual DOM manipulations away from the developer, helping us to write more predictable code. It does so by comparing two render trees to determine exactly what has changed, only updating what is necessary on the actual DOM.
Subscribe to my newsletter
Read articles from Naveen Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by