React Real DOm Virtual DOM


Virtual DOM :

A virtual DOM is a lightweight JavaScript object which originally is just a copy of the real DOM.
the concept of virtual DOM comes in and performs significantly better than the real DOM. The virtual DOM is only a virtual representation of the DOM. Everytime the state of our application changes, the virtual DOM gets updated instead of the real DOM.

How is Virtual DOM faster?

When new elements are added to the UI, a virtual DOM, which is represented as a tree is created.
Each element is a node on this tree. If the state of any of these elements changes, a new virtual DOM tree is created.
This tree is then compared or “diffed” with the previous virtual DOM tree.
Once this is done, the virtual DOM calculates the best possible method to make these changes to the real DOM.
This ensures that there are minimal operations on the real DOM.
Hence, reducing the performance cost of updating the real DOM.

How does React use Virtual DOM ?

Now that you have a fair understanding of what a Virtual DOM is, and how it can help with performance of your app, lets look into how React leverages the virtual DOM.
In React every UI piece is a component, and each component has a state.
React follows the observable pattern and listens for state changes. When the state of a component changes, React updates the virtual DOM tree.
Once the virtual DOM has been updated, React then compares the current version of the virtual DOM with the previous version of the virtual DOM. This process is called “diffing”.
Once React knows which virtual DOM objects have changed, then React updates only those objects, in the real DOM.
This makes the performance far better when compared to manipulating the real DOM directly.
This makes React standout as a high performance JavaScript library.