What is Virtual DOM in React and How Virtual DOM works?

    May 15, 2019       by Suraj Roy
react-virtual-dom.png

For me its always a confusing question, What is virtual DOM and how it works differently then Real DOM?

Manipulation of DOM is the heart of Single Page Application of javascript front-end frameworks. To work with DOM directly is slower, because most of the frameworks update the DOM many times. Every time we update the DOM, browser need to recalculate the design of CSS, do layout, and repaint the web page. These tasks make everything slower.

To resolve this issue, the React team started the new concept of updating the DOM using virtual DOM. 

 

React Virtual DOM

In React, Each time the DOM updates or data of page changes, a new Virtual DOM representation of the user interface is made. It's just a lightweight copy or DOM.

Virtual DOM in React has almost same properties like a real DOM, but it can't directly change the content on the page. As I said earlier that working with Virtual DOM is faster as it does not update anything on the screen at the same time. In a simple way, Working with Virtual DOM is like working with a copy of real DOM nothing more than that. 

Updating virtual DOM in ReactJS is faster because ReactJS uses

  1. It's efficient diff algorithm.
  2. It batched update operations
  3. It efficient update of sub tree only
  4. It uses observable instead of dirty checking to detect change

 

How Virtual DOM works in React

When we render a JSX element, each virtual DOM updates. This approach updates everything very quickly. 

Once the Virtual DOM updates, React matches the virtual DOM with a virtual DOM copy that was taken just before the update

By Matching the new virtual DOM with pre-updated version, React calculates exactly which virtual DOM has changed. This entire process is called "diffing."

When React knows which virtual DOM has changed, then React updated those objects. and only those object, in the real DOM.

React only updates the necessary parts of the DOM. React’s reputation for performance comes largely from this innovation.

In brief, here’s what happens when we update the DOM in React:

  1. The entire virtual DOM gets updated.
  2. The virtual DOM gets compared to what it looked like before you updated it. React matches out which objects have changed.
  3. The changed objects and the changed objects only get updated on the real DOM.
  4. Changes on the real DOM cause the screen to change finally.

 

Conclusion

So in this article, I tried to clear all about React Virtual DOM in brief. You can find  React sample projects here.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.


WHAT'S NEW

Find other similar Articles here: