loading...
Cover image for The best example to understand virtual DOM

The best example to understand virtual DOM

maulik profile image Maulik ・2 min read

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.

Posted on by:

maulik profile

Maulik

@maulik

An ever-smiling full-stack developer, specializing in the rapid development of custom web applications. Always eager to learn new technologies and concepts and share knowledge.

Discussion

pic
Editor guide
 

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.

 

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.

 

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

 

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-...

 

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

 

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

 

Great example. Easy to understand. Thanks.

 

Thank you, Glad that you liked it.

 

This example was really helpful!

 

Glad it helped you. Thanks