ReactJS DOM VS Virtual DOM - ReactJS Tutorial



DOM Vs Virtual DOM

What is Real/Browser DOM ?

  • DOM stands for "Document Object Model". It denotes the entire UI of the web application as a tree data structure.
  • It is a basic representation of the HTML elements of the web application.
  • Whenever there is a change in the state of application UI, the DOM gets updated and represents that change.
  • With every change, the DOM gets manipulated and re-rendered to update the application UI, which affects the performance and makes it slower.
  • Hence, with more UI components and complex structure of the DOM, the DOM updates will be more costly as with every change it needs to be re-rendered.

DOM in HTML Javascript


What is React Virtual DOM ?

  • To make the performance of the Real DOM quicker and better, the idea of Virtual DOM shows up. The Virtual DOM is only the virtual picture of the DOM.
  • But the difference is, each time with each change , the virtual DOM gets reorganized instead of the real DOM.
  • Like, real DOM , virtual DOM is also denoted as a tree structure. Every element is a node in this tree.
  • When a new item is added to the application UI, a node is added to the tree also.
  • If the state of any of these components changes, another virtual DOM tree is created.
  • The virtual DOM figures the most ideal way or we can say the small procedure on the real DOM to make changes to the real DOM.
  • Hence, it makes efficient and better performance by reducing the cost and operations of re-rendering the whole real DOM.

Now that we have the basic understanding of Real and Virtual DOM, let's focus on how React works using the Virtual DOM.

  • In React, each UI is an different component and each component has its individual state.
  • React follows the visible pattern and detects the changes of the states.
  • Whenever a change is made in the state of any component, React updates the virtual DOM tree but does not change the real DOM tree.
  • After updating, react compares the recent version of the virtual DOM with the earlier version.
  • React knows which objects are altered in the virtual DOM, based on that it only changes those objects in the Real DOM, making minimum working operations.
  • This process is noted as "diffing". A picture below will clear the concept more.
  • Here the red circles are the nodes that has been changed. That means, the state of these components is changed. React computes the difference of the previous and current version of the Virtual DOM tree and the whole parent sub-tree gets re-rendered to show the changed UI.
  • Then the updated tree is batch updated (This means that updates to the real DOM are sent in groups, instead of sending updates for every single change in state.) to the Real DOM.

Related Searches to ReactJS DOM VS Virtual DOM