Virtual DOM

Document Object Model a.k.a. DOM is a cross-platform and language-independent programming interface. It treats various types of documents such as HTML, XML as tree structures consisting nodes as objects. These objects can be manipulated using DOM API. Virtual DOM is an in-memory replica of the DOM which is used by certain Javascript libraries to achieve certain performance goals.

What is Virtual DOM?

Virtual DOM is an in-memory copy of the Real DOM. When you use javascript to modify any element in the HTML, you are modifying the DOM. When the DOM is modified, it needs to spend a great deal of time in computing the exact changes, applying them and re-rendering the entire DOM. By maintaining Virtual DOM, one can easily identify the complete set of changes and apply them to the real DOM all at once. This helps in saving time to apply the changes, which could have happened iteratively.

Updating Virtual DOM - pictorial representation [Source: https://medium.com/@hidace/understanding-reacts-virtual-dom-vs-the-real-dom-68ae29039951]
Updating Virtual DOM – pictorial representation [Source: https://medium.com/@hidace/understanding-reacts-virtual-dom-vs-the-real-dom-68ae29039951]
There are two ways in which a library can find out what has changed:

  • Dirty Check
  • Observable

In dirty checking method, all the nodes are checked at regular interval to see if something has changed. This makes it a very slow process. Whereas in “observable” method, components simply listen to state changes and decide when to re-render the UI.

So what is the real advantage of having a Virtual DOM?

React framework uses Virtual DOM heavily. It maintains a copy of real DOM in memory referred as virtual DOM. All the changes are first done to virtual DOM. Later it uses a technique called “diffing” to find out the exact changes to be made to the real DOM. Only this “diff” is then applied to real DOM thereby minimizing the overhead of finding out changes iteratively.

Related Links

Related Keywords

ReactJS, AngularJS, DOM

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.