DOM vs. Virtual DOM

React acting like a complete BOSS!

Document Object Model or DOM is a tree-like structure of a web page, consisting of nodes and objects, that the browsers create when a web page is loaded.

graphical representation of the DOM (source: w3c)

Talking specifically, DOM acts as a programming interface for HTML and XML documents. Hence, it can be said that DOM is the heart of the modern and interactive web. But its major drawback comes when we talk about speed. DOM is a lot slower than most JavaScript operations. Since most of the Javascript frameworks update DOM much more than they have to, it makes the DOM even worse!

Let's take an example. Suppose you are creating a to-do list app that lets you add elements to it and also strike off the things that are completed. Now, when you run this web app, suppose you add 5 items to it. The Javascript framework will create a list of these 5 items. Now suppose you strike off 1 item as it has been done. Most of the JavaScript frameworks will again create an entire list of remaining 4 items and the one that got strike off. This means that even if only 1 item is getting changed, the remaining 4 get rebuilt exactly how they were before. Now the modern websites will use a huge amount of DOM manipulation for this and will make it slower. To overcome this, Virtual DOM comes into the picture.

Virtual DOM

From above, one can understand that DOM is the heart of the modern web. But its major drawback comes when we talk about speed. React, the most widely used JavaScript library nowadays makes use of virtual DOM. React creates a virtual DOM for every DOM object. Thus, you can say that the virtual DOM object is like a lightweight copy of the DOM object.

A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing’s power to directly change what’s on the screen. Since using the virtual DOM object, nothing gets drawn onscreen, manipulating it is a lot faster than DOM.

React builds a virtual DOM when we render a JSX element and gets updated whenever we render a JSX element. What's interesting to know here is that React keeps a copy or snapshot of the pre-updated virtual DOM. Whenever an update takes place in the virtual DOM, React compares the updated virtual DOM with the screenshot of the pre-updated virtual DOM. This comparison is made in order to figure out which virtual DOM got changed. Once it figures out, it only updates those objects in the real DOM which got updated.

As such, only the necessary parts get updated. For more details, visit this link.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adwiteeya Reyna

Adwiteeya Reyna

Software Developer | Web Developer | Database Developer