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 😷