React’s Virtual DOM
A key component of React is its virtual DOM, a compact, in-memory duplicate of the real DOM, that enables React to effectively track UI changes and update only the necessary components, boosting rendering speed and effectiveness and enhancing the general performance of web apps. This article focuses on how the Virtual DOM works and explains how it optimizes application performance compared to the Real DOM.
The DOM refers to the “Document Object Model”; it represents and interprets a website written in HTML to the browser. When you write HTML, the browser does not understand it, and therefore when a webpage is loaded, the browser parses the HTML into an Object hence the name “Document Object Model”.
The DOM is the form in which the browser understands HTML and gives us a visual representation once the page is loaded. The object created contains properties and methods which enable developers to manipulate the DOM using scripting languages such as Javascript.
HTML elements tags are represented as element nodes in the DOM, and we also have text nodes and attribute nodes present in the DOM.
<div id="myDiv">This is an example of an element node</div>
Element nodes represent HTML element tags such as div,p, and tags. They all represent the respective tags as element Nodes in the DOM.
<p>
This is an example of a text node within a <strong>paragraph</strong> element.
</p>;
An object that symbolizes text inside of an HTML element is called a text node. An element node’s children are always text nodes.
We can change the content of the paragraph above by manipulating the DOM using Javascript properties and methods such as:
let text = document.querySelector('p')
text.innerText = "Hello there!!"
With the innerText property, we have been able to change the content of the paragraph tag by directly manipulating the DOM.
The Difference between the Real DOM and Virtual DOM
The browser uses the Real DOM to update the webpage when working with Javascript without a framework. But the browser uses the Virtual DOM when working with a framework such as React.
Think of the Real DOM this way:
Imagine you have a metal box with a colored ball inside it, and every ten seconds, you have to change the ball inside that box to another ball with a different color.
Every ten seconds, you unscrew the box at the edges, open it up, remove the former ball, and replace it with a new ball, before fixing the metal box back in place. This analogy explains how the Real DOM works when a state change happens.
When dealing with the Real DOM, it “replaces an element in place” This refers to replacing an existing element with a new one when a state change occurs.
In other words, a new element with the modified content is added to the DOM instead of the removed element. This can be costly because it requires recalculating the layout and style of the entire subtree, especially if the element has a sizable subtree of child elements.
Replacing the previous element with a new element, in this case, mirrors unscrewing and re-screwing the metal box every single time you needed to change the ball inside it.
Think of the Virtual DOM this way:
You have the same Metal Box and must carry out the same procedure. But this time, you have a robot friend who assists you in changing the ball in the box; all the robot has to do is lay hands on the box, and the ball in the metal box will change.
The opposite of “replacing the element in place” in the Virtual DOM is “updating the element in place”.
Only the portions of the element that have changed due to the state or prop updates are updated by the Virtual DOM instead of completely replacing the element with a new one.
Because it requires fewer calculations to update the element and its descendant components, this strategy is more effective than changing the element entirely.
One of the key benefits of using a Virtual DOM is the ability to change the element in place quickly and effectively without having to perform the pricey recalculations required when updating the real DOM directly.
Now, this analogy is only trying to tell you that the virtual DOM works faster and cheaper than the real DOM.
Session Replay for Developers
Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay suite for developers. It can be self-hosted in minutes, giving you complete control over your customer data.
Happy debugging! Try using OpenReplay today.
Creating and Updating Elements in the Virtual DOM
When working with the React framework, you are no longer updating the content of your website with just the Real DOM; this update occurs with the help of the virtual DOM.
Once your browser is loaded up, React copies the DOM object, which is called the Virtual DOM.
Consider the Virtual DOM to be a duplicate of the Real DOM. The Virtual DOM can alternatively be seen as the Real DOM’s blueprint.
The sole difference between the Virtual DOM and the Real DOM is that updates to the website only occur when the Real DOM is updated. Both have the same capabilities.
Remember how you could compare the virtual DOM to a building’s blueprint earlier? It is best to make those changes quickly and easily on the blueprint before implementing them to the main building.
Using this blueprint, you can quickly make first-hand changes instead of going ahead and making changes to the real building. That would be too tedious, and if you have a lot of changes to make to the building, you might make mistakes along the way.
Once the webpage is loaded, the Real DOM and the Virtual DOM look the same; no changes have been made.
Assume you have a button that modifies an element’s state when clicked. React immediately produces a new Virtual DOM, which we may refer to as the Updated Virtual DOM or the Current Virtual DOM, when that state change occurs.
Once that happens, React has a copy of two virtual DOMS. The old version and the updated version with the state change.
There has not yet been any change to the website because the virtual DOM that is currently active holds the state change that has just taken place rather than the real DOM.
The image above shows that the purpled-colored box represents the state change, but this change happens first in the virtual DOM.
React must now compare the updated virtual DOM with the previous virtual DOM, the two versions of the virtual DOM. The comparison determines whether there is any difference between the two; if not, the Real DOM is left just as it is.
This comparison between the two versions of the virtual DOM is called the diffing process.
But in this case, it is seen that there was a state change on the element with the purple color.
React takes note of the particular state that was changed and then changes only that state in the Real DOM instead of rebuilding the entire parts of the DOM associated with that element.
This process is called reconciliation.
Let’s use the Elements tab in the developer tools to preview a visual comparison of how the DOM is changed when dealing with the real DOM and the virtual DOM.
The above example solely uses the Real DOM, and as you can see, when the button is clicked, the only thing that changes on this webpage are the numbers, which are increased by 1.
However, the h2 and p tags are highlighted if you look at the developer tools on the right. This highlight lets people know that a new element is placed whenever the number of counts changes.
The virtual DOM is used in this illustration. The count goes up by 1, just like in the previous illustration.
Nevertheless, you’ll see that only the number is highlighted if you look at the developer tools on the right.
Compared to the last example, the element that encloses the number is not highlighted.
This means that the element was not modified or replaced; rather, the virtual DOM allowed for the replacement of only the state that had changed.
Limitations of the Traditional DOM approach
- Performance: The conventional DOM technique can be time-consuming and memory-intensive for large documents. The reason for this is because the entire page is loaded into memory, it must be updated every time something is changed, which can take some time.
- Complexity: Working with the DOM tree can be challenging, especially for developers new to web programming. As a result, the code could be challenging to read, comprehend, and maintain.
- Restricted interactivity: The conventional DOM technique is not optimal for dynamic, interactive applications. While filling out a form, the user may need to render the entire document each time they enter a new character, which can be tedious and cumbersome.
- Difficulty of scalability: Scaling large, sophisticated applications using the conventional DOM method is difficult. The DOM tree can become cumbersome and challenging to manage as the application expands in size and complexity.
Benefits of working with the Virtual DOM
- Improved user experience: The virtual DOM can offer a better user experience by requiring less work to update the DOM. Applications created with the help of the virtual DOM can refresh their user interface more quickly, react to user interactions more quickly, and offer a more seamless experience in general.
- Development Process Optimized: The virtual DOM optimizes development by using a declarative programming model. Developers may now declare how they want the application to look, and the virtual DOM will take care of the rest, according to this. This strategy can lessen the amount of code required, increase readability, and facilitate codebase maintenance.
- Increased performance: By lowering the number of updates required to the actual DOM, the virtual DOM can greatly increase the performance of online applications. Instead of modifying the actual DOM directly, it accomplishes this by constructing a virtual version of the DOM and making changes to it. Once all the updates have been completed, the virtual DOM only makes the necessary updates to the actual DOM, minimizing the overall amount of work required.
Conclusion
All things considered, the virtual DOM is a strong programming idea that assists programmers through the react library in building effective and high-performance web apps while simplifying development and enhancing user experience.