DEV Community

loading...
Cover image for What is Virtual DOM? How Virtual DOM works ? What is Reconciliation ? What is diffing algorithm? What makes React so fast ?

What is Virtual DOM? How Virtual DOM works ? What is Reconciliation ? What is diffing algorithm? What makes React so fast ?

Kishan Sheth
I am a kind of guy who likes programming at its core; excellent communication as well as leadership skills. Detail oriented and organised professional.
Updated on ・4 min read

You can also refer to my YouTube video for understanding with animations about the Virtual DOM.

To learn virtual DOM you should also have some basic idea about the DOM.

What is DOM?

DOM stands for Document Object Model. It is the hierarchical representation of your web page(UI). For Example you have a blog website, so the hierarchical representation of the website would be as follows.

Blogging Website DOM

This is how the browser renders your web page. This is called DOM.

If there was already DOM then why was the concept of virtual DOM implemented?
Because DOM manipulation is very slower. Consider the blogging website example and in any of the blog post if a user modifies a comment then the whole DOM (UI) needs to be repainted because of that one little change. This change is very expensive in terms of time complexity.

To solve this problem here comes our hero Virtual DOM.

What is Virtual DOM ?

In simple words, virtual DOM is just a copy of the original DOM kept in the memory and synced with the real DOM by libraries such as ReactDOM. This process is called Reconciliation.

Virtual DOM has the same properties that of the Real DOM, but it lacks the power to directly change the content of the screen.

Think of Virtual DOM as the blueprint of a machine, changes made to the blueprint doesn't reflects on the machine itself.

How Virtual DOM works ?

So when there is a update in the virtual DOM, react compares the virtual DOM with a snapshot of the virtual DOM taken right before the update of the virtual DOM.

With the help of this comparison React figures out which components in the UI needs to be updated. This process is called diffing. The algorithm that is used for the diffing process is called as the diffing algorithm.

Once React knows which components has been updated, then it replaces the original DOM nodes with the updated DOM node.

Let's understand this with a Example.

Initial DOM

<section>
         <div>
               <h1>Hello React</h1>
         </div>
         <div>
               <h1>Hello React 2</h1>
         </div>
</section>
Enter fullscreen mode Exit fullscreen mode

Updated DOM

<section>
         <div>
               <h1>Hello React</h1>
         </div>
         <div>
               <h1>Hello React 5</h1>
         </div>
</section>
Enter fullscreen mode Exit fullscreen mode

Now here when there is update in the UI then react compares the new virtual DOM with the pre-updated virtual DOM and points out that in the second <div> the content has been changed so it only updates the content of the second div in the real DOM.

This process is fast as only a single node had to change as opposed the whole repainting of the UI.

But wait what if the DOM elements are added ?

<section>
         <div>
               <h1>Hello React</h1>
         </div>
         <div>
               <h1>Hello React 5</h1>
               <h2>Hello React 17<h2>
         </div>
</section>
Enter fullscreen mode Exit fullscreen mode

In this scenario only a node has been added to the second div so React just adds it to the real DOM.

But wait here the element was added at the end of the div element.

What if we add an element at the top ?

<section>
         <div>
               <h1>Hello React</h1>
         </div>
         <div>
               <h2>Hello React 17<h2>
               <h1>Hello React 5</h1>
         </div>
</section>
Enter fullscreen mode Exit fullscreen mode

here the virtual DOM would repaint the whole second div as when it tries to compares it with the pre-updated virtual DOM then in second div the first child was h1 and now it is h2 so it doesn't just add the new element instead it replaces the whole div element.

Imagine that instead of just the two elements inside the second div tag we have 1000's of hierarchical components. It will re-render those 1000's of components which didn't changed.

To solve this issue React supports a key attribute. When the children of the React components have keys, React uses the keys to match children in the pre-updated virtual DOM.

Let's use these keys in our example above and see how it solves our problem.

<section>
         <div>
               <h1 key="as231">Hello React</h1>
         </div>
         <div>
               <h2 key="12dsa">Hello React 17<h2>
               <h1 key="asddda">Hello React 5</h1>
         </div>
</section>
Enter fullscreen mode Exit fullscreen mode

Here now react diffing algorithm matches the component with previous key asdda in the second div and a new element with key 12dsa. So in this scenario react just marks the new element and it is added to the real DOM. This solves our problem of unnecessary re-rendering of unchanged components.

Make sure the following points when using keys :

  • React keys should be different in sibling components, not globally.
  • You can also pass the array index as the key.
  • You can also pass the id received from the database.

Now you know what makes React so fast ? It's the use of virtual DOM which keeps the re-painting of the DOM as less as possible.

RECAP

  • Frequent DOM manipulations are expensive.
  • Virtual DOM is a virtual representation of DOM in memory.
  • Virtual DOM is synced with real DOM with ReactDOM library. This process is called Reconciliation.
  • React compares the Virtual DOM and pre-updated Virtual DOM and only marks the sub-tree of components that are updated. This process is called diffing.
  • The algorithm behind diffing is called Diffing algorithm.
  • React uses keys to avoid unnecessary re-renders.

Discussion (16)

Collapse
inhuofficial profile image
InHuOfficial • Edited

Any reason to delete my comment? The below is the original comment and is designed to be useful to your post and understanding not as any criticism! I wouldn't have hearted your post if I thought it wasn't good 😀

Virtual Dom is slower than the actual DOM and vanilla DOM manipulation.

Where the benefits come are from the fact that if you update 5 different items the virtual DOM can be used as a tool to automatically decide exactly what needs to change.

Doing document.querySelector(#someID).innerHTML = "apple" will be magnitudes faster than any framework as you have the overhead of calculating the differences in the virtual DOM before and after in a framework.

The virtual DOM is useful if you don't know what element will change before hand, which is why it is used and necessary for frameworks like React.

All that React is doing "under the hood" is automatically isolating elements that need updating.

So in the example you gave of a comment being added needing to repaint the whole DOM that is nonsense. You can just do document.querySelector('#comments').appendChild(ourNewElement); and that will not repaint the whole UI, just the bit that needs updating and any content below it - that is all that frameworks are doing in the background, but in a way that makes our life much easier as developers!

Collapse
koolkishan profile image
Kishan Sheth Author

That was very unprofessional of me to delete your comment. I apologise for that. Thank You for pointing this out.

Collapse
inhuofficial profile image
InHuOfficial

Nah don't worry, I can see from how I phrased it it looked like an attack, that is why I added the first bit! Enjoyed the article! ❤

Collapse
quochuytlbk profile image
Huy Ta Quoc

Maybe this is not directly related to the article but I want to point out that "being fast" is actually not a selling point of React. At least not for me. I think most people don't use React because it's fast. In fact, React is often slower and heavier than its competitors out there (e.g. Svelte, Vue 3, Preact, etc.).

Collapse
thesanjeevsharma profile image
Sanjeev Sharma

So, why do people use it? Community? Or is it easy than others?

What's your view?

Collapse
quochuytlbk profile image
Huy Ta Quoc

I don't think React is easier to use than the others. It has certain gotchas that even experienced React developers sometimes stumble upon (e.g. stale states, stale closures). You also need to manually prevent the application from not re-rendering components too much (by using useMemo, useCallback, memo, etc.) or there'll be performance issues. There are also a few more things that people who are new to React will have a hard time wrapping their mind around.

So, it is slower, heavier, and more complex than its competitors. Why do people still use it then? I guess it's because React just happens to be one of the first groundbreaking technologies of its kind. If, for example, SolidJS (the fastest and lightweight library that has somewhat similar APIs to React) had been there instead of React, I guess it would become as popular as React right now.

For me personally, the reason I still use React is because of its ecosystem. React is so popular that you can almost find a mature, invested solution to any problem you're facing out there, written in React. That's not something you can easily find in its competitors.

Thread Thread
vahlcode profile image
Valentine Elum

Exactly.

Collapse
ogranada profile image
Andres Granada • Edited

Great article. Very explicit, however according to svelte.dev/blog/virtual-dom-is-pur... (found in dev.to/jannikwempe/why-svelte-is-d...) developers would have to have in mind the cons about the Virtual DOM.

Collapse
peerreynders profile image
peerreynders • Edited

According to JavaScript Frameworks, Performance Comparison 2020 Inferno and Hyperapp which are both VDOM-based have no trouble keeping up with Svelte.

React likely chose VDOM rendering to decrease coupling to the browser platform (i.e. pursuing an entirely different set of trade-offs) - which comes at a cost (The DOM Is NOT Slow, Your Abstraction Is).

Ostensibly React became popular due to perceived (subjective) developer ergonomics, not performance.
(personally I preferred Svelte's ergonomics)

Collapse
rishiagarwal95 profile image
Rishi Agarwal

Great article... But this point where you say
'You can also pass the array index as the key.'
So this is sort of an anti - pattern in react , we should not pass index as keys since it leads to some issues. You can read more about it in official docs.

Collapse
himanshhhu profile image
Collapse
koolkishan profile image
Collapse
n3m3s7s profile image
Fabio Politi

I simply love Dev.to: It Is not rare that you Will find much more context and knowldege in the comments than the post itself.

Collapse
mshinozaki profile image
Márcio Shinozaki

Great article.

Collapse
princedede profile image
Tserundede Ejueyitchie

Thanks for this! I am.a newbie be im web development and hopefully i would be learning so much from you

Some comments have been hidden by the post's author - find out more

Forem Open with the Forem app