DEV Community

Cover image for React Virtual DOM Explained in Plain English
Aditya Sharan
Aditya Sharan

Posted on • Updated on

React Virtual DOM Explained in Plain English

We still don't catch how Virtual DOM works. Actually, what is DOM? They say Document Object Model. Well, but what is it exactly? The DOM in simple words represents the UI of your application.

Let's dive in.

When a browser downloads the HTML document it creates the tree-like representation of that document, the so-called Object Model where every HTML tag has its corresponding node.

In that way, Javascript gets access to the HTML tags and can change them: add styles, modify or even delete them.

Making these changes is not slow. What makes the process slow and costly is how the browser organizes those changes. In every update, HTML parser reads the HTML document then DOM is being created, at the same time CSS parser parses the stylesheets and applies style rules. As a result of the process, Attachment is being created. Afterward, Layout process gives the exact co-ordinates to each node of the render tree, i.e. each element's exact coordinates on the screen.

So the Render tree is ready, then go Painting and Display.

What makes DOM manipulation slow?

Updating DOM is a slow and expensive process
You have to traverse DOM to find a node and update it.
Updating DOM has cascading effects - things need to be recalculated.

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

Well, you may ask ” Isn’t the virtual DOM doing the same thing as the real DOM, this sounds like double work? How can this be faster than just updating the real DOM?”

How is Virtual DOM faster?

Alt Text
There are always two versions of VDOM. One is before the changes and the other is after the changes. So when changes occur React compares two VDOMs and detects the changes.
This process is called ''diffing''.

Alt Text

The changed objects only get updated on the real Dom. Changes in the real DOM cause the screen to change. This is called ''reconciliation''.

VDOM is like a blueprint and making changes in it is more efficient.
Instead of rendering all changes to the real DOM, we apply them first to the Virtual DOM, which is doesn't get rendered. So the changes to it are very cheap.

Thanks for reading!

Oldest comments (0)