A bit clearer about the Virtual DOM in ReactJS

Tram Ho

Content:

If you have done any SPA application with reactjs then reloading page when doing DOM changes from small changes like clicking like a post on facebook, to redirecting won’t happen. out. You may have heard of React VirtualDOM but how it works and what algorithm it applies to, I will introduce it in this article.

First, I first go into the concept of DOM and Virtual DOM

  • The DOM (Document Object Model) is the programming interface for HTML and XML documents, it defines their logical structure and how they are accessed and manipulated. When a web page is loaded, the browser creates DOM for that page in the form of object nodes with the following basic model:
  • Because creating and updating the DOM is quite time consuming, the facebook development team created a Virtual DOM to speed up DOM updates in its ReactJS application.
  • Virtual DOM is designed to be compact, and its essence is an Object that copies the DOM created by the browser.

Virtual DOM works in 3 steps:

  • When the state or prop changes, the entire UI will re-render in the Virtual-DOM
  • Check the difference between DOM and Virtual DOM according to difference test algorithm
  • Update DOM with the changes found using the algorithm in step 2:

Now to the algorithm section to check the difference:

  • When comparing two trees (here you understand DOM and Virtual DOM), react compares the root of two trees. When the root changes, the entire tree will be destroyed and rebuilt. when the tree is destroyed, unmout operations will be called as clear cache execution, remote event listener … And vice versa, in the new containment operation the initialization operations will be executed. Since the root doesn’t change, react keeps checking the properties of the element, if it changes it just updates this part. For example:

Here, when compared, React will tell us that the className has changed

  • After comparing root is comparing child elements: React will iterate over all child elements of the parent node simultaneously and make 1 transformation every time a change element is encountered. Each child element if it is a list of the same elements must have a separate key for react to know and only update the correct location where the key changes eg:

Conclude:

Hope this post will help you understand more about ReactJS, nice coding.

References:

Share the news now

Source : Viblo