Why does React use a Virtual DOM?

Good day, guys! Today, I’ll explain why React employs a virtual DOM on top of the real DOM, and how it increases overall performance significantly.

The Issue with the Real DOM

When a web page is loaded into a browser, the browser produces a DOM (Document Object Model – More on this subject) for that page. When we make a modification to the code, the DOM must be re-rendered to reflect the changes we’ve made. The performance of the DOM degrades as the structure becomes more complex.

Virtual DOM to the rescue

React uses a virtual DOM (VDOM) where the virtual DOM has the same structure as the real DOM. When we do a code change, React makes the change in the virtual DOM instead of the real DOM.

As we know, just like the real DOM, virtual DOM has a tree structure. When a code change is made, a new virtual DOM is created. Then the new virtual DOM is compared (“diffed”) with the old virtual DOM.

After that, React figures out the best possible way to change the real DOM. This process is called reconciliation. There is a great in-depth article in React Website regarding this. I’d like to recommend you to read that article to understanding what things React considered in this process.

From the React version 16 onwards, React uses a new reconciliation engine called React Fiber. You can read regarding React’s Fiber architecture from here.

So, VDOM is faster than the DOM then?

Well, No. VDOM is not faster than DOM. The reason why React uses a virtual DOM is so that they can implement their own algorithm and find out where exactly should be changed in the real DOM. And after that, they can just re-render only the changed nodes without recreating the whole DOM. Obviously, this makes React’s process significantly faster.

Is VDOM the only solution?

No. There are other languages like Svelte that do not use a virtual DOM and still get the job done. You can read the following article to understand the difference between React and Svelte.

Well, I hope you learned something value from this article. If you have any questions, please drop a comment. Until next time, stay safe 😷

Published by Thisura Thenuka

I am a passionate software engineering student. But cricket is my first love ❤

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: