What is a virtual DOM?
The virtual DOM (VDOM) is a programming concept in which an ideal, or “virtual,” version of a user interface (UI) is stored in memory and synchronised with the “actual” DOM via a library such as ReactDOM. This is known as reconciliation.
This method provides the declarative API of React: You tell React what state you want the UI to be in, and it ensures that the DOM matches. This abstracts off the attribute manipulation, event handling, and manual DOM updates that you would have to utilise to develop your app otherwise.
How does Virtual DOM actually work?
React compares the Virtual DOM to a snapshot of the original state before the change for each update to the Virtual DOM. So, with the help of this comparison performed by react js, it automatically determines which section of your react component need updating. React, interestingly, employs what we call the diffing algorithm to accomplish this, and the process of applying this diffing technique is referred to as diffing. So, after comparing, responds changes the components that need to be updated with the updated nodes. Let’s have a look at some sample code to see how it works:
Initial DOM State:
Update DOM State:
When the DOM is updated, it just updates the content of the DOM, as shown in the second block of code. This update happens so quickly that we frequently don’t see it. It merely marks the component that needs to be updated and does the change for us.
The Functional aspects of Virtual DOM
It is clear that the performance provided by the Virtual DOM is amazing. Not only that, below are some advantages of the Virtual DOM:
- Speed and performance boost
- It is simple and clear
- Amazing diffing algorithm
- It can be used on other frameworks not just react
Well, anything which has an advantage will have a disadvantage too, let us consider the drawbacks of virtual DOM:
- Higher memory usage problems as the diffing algorithms need to keep comparing the elements to know which components needs to be updated or changed.
- It is not easily integrated into many other frameworks.
- You can’t use it or target template engines.
Even at the cons mentioned above, virtual DOM is always the go-to because of the boost in performance and speed it offers.
What can we conclude?
The Virtual DOM is not going away, since many libraries, frameworks, and tools have adopted its use to improve the performance of the services their tools deliver. It provides a really excellent approach of decoupling all of your application’s logic from the requirement to change the DOM. All you have to do is write your business logic, and it will handle the DOM update for you.
Article source: How Virtual DOM in React Works and Why It Matters?
No comments yet
Sign In / Sign Up