What is the difference between virtual and real DOM (React)?

DOM is the abstraction of the HTML of a web page. With the advent and popularity of dynamic web pages and SPASingle Page Applicationss, DOM has proven to be very inefficient and expensive when updating items.

Consider a list of numbers, as shown below:

              [1,2,3,4,5] [1,2,3,4,5]

Suppose we wish to replace 33 with 66. For this, we'll create an entirely new list, as shown below:

              [1,2,6,4,5] [1,2,6,4,5]

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.

Virtual DOM

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 process of updating in React

  1. The ReactDOM.render() renders the elements on the screen on the first load by creating the real and virtual DOM trees.

  2. 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.

  3. 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.

  4. 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 process of updating in React

Difference between virtual and real DOM

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.

Copyright ©2024 Educative, Inc. All rights reserved