DOM is the abstraction of the HTML of a web page. With the advent and popularity of dynamic web pages and
Consider a list of numbers, as shown below:
Suppose we wish to replace
Another, more efficient way to do this is to go to the required index in the array and update it in place. This is a small example, but with thousands of nodes on a single page, the process of updating every node (re-rendering it) negatively affects the performance of the page.
The virtual DOM is the abstraction of the real DOM. In other words, it is the abstraction of an abstraction. A virtual DOM object is the same as a real DOM object, except that it is a lightweight copy. This means that it cannot manipulate on-screen elements. Moreover, upon any change of a property, it only updates the corresponding nodes and not the entire tree. That makes it a quick and efficient alternative.
The ReactDOM.render() renders the elements on the screen on the first load by creating the real and virtual DOM trees.
Any change to an element (such as a key press or button click) leads to a notification sent to the virtual nodes for a state change. If any property of the node is altered, it updates itself.
React compares the updated virtual DOM with the real DOM and updates the real DOM accordingly. This process is known as reconciliation. This is done using a heuristic algorithm known as the Diffing Algorithm.
The updated real DOM is rendered on the screen.
The illustration below outlines this process. The purple nodes represent the elements rendered on the first load, while the red node is the updated element due to user interaction. Initially, the real and virtual DOM trees are identical. Upon a change in an element, the virtual DOM tree is updated and compared to the real DOM, which is also updated.
The differences between virtual and real DOM are summarized in the table below:
Real DOM | Virtual DOM |
It is an abstraction of a page's HTML. | It is an abstraction of an HTML DOM. |
It can manipulate on-screen elements. | It cannot manipulate on-screen elements. |
Any change updates the entire DOM tree. | Any change only updates the relevant node in the tree. |
Updating is slow and inefficient. | Updating is fast and efficient. |