DEV Community

Cover image for The best example to understand virtual DOM
Maulik
Maulik

Posted on

The best example to understand virtual DOM

The virtual DOM is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM.

So generally libraries and frameworks which provide virtual DOM functionality implement virtual tree of UI nodes and on change or re-rendering process, it will check the new node tree with the older node tree that is virtual DOM and then call browser DOM API to re-render only the part that has been changed.

Let's understand this by actual example.

The above example is simply re-rendering the content in the div element with root Id. So if we see in the developer tools of the browser, we see something like this
GIF

So, the whole root content is getting re-rendered every time.
Now let's use react to do the same

It's time to check the element rendering in the developer tools of the browser and see what we get...
Alt Text

Guessing you have seen the virtual DOM magic in the above example. Frameworks and libraries like Vue and React use virtual DOM for this purpose.

Virtual DOM provides us optimized update process and the freedom to not think much about the rendering process (Even if we are re-rendering the whole UI it will actually re-renders the change) but as there is always price to pay and here the price is in the form of high-memory consumption of storing the copy of dom and checking the difference every time something re-renders.

Discussion (10)

Collapse
z00md profile image
z00md

I can't say if its the best example, but you did manage to showcase the Optimized update process which is difficult to visualize specially in these small examples.

Collapse
maulik profile image
Maulik Author

Thanks for the feedback. You are correct, this may not be the best example. I have delivered a few sessions where I have given this same example and people loved it so I have posted it here thinking it will be easy for others to understand through this example.

Collapse
perpetual_education profile image
perpetual . education

What IS the best example! We're excited to see the update ;)

Collapse
ycmjason profile image
Jason Yu

Nice demonstration!

I wrote an article (and gave a talk) on how to create your own simple virtual dom from scratch. Check it out. 👍

dev.to/ycmjason/building-a-simple-...

Collapse
maulik profile image
Maulik Author

Thanks Jason. I will surely have a look at your article

Collapse
firewalker06 profile image
Didik Wicaksono

TIL that virtual DOM provides optimized updates. This example is easy to understand. Thanks!👍

Collapse
halloleo profile image
halloleo

Great example. Easy to understand. Thanks.

Collapse
maulik profile image
Maulik Author

Thank you, Glad that you liked it.

Collapse
chrstnfrrs profile image
Christian Farris

This example was really helpful!

Collapse
maulik profile image
Maulik Author

Glad it helped you. Thanks