DEV Community

Karthik Raja
Karthik Raja

Posted on

What is Virtual Dom? And Why is it faster?

According to React docs virtual DOM is

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM

Before diving into virtual DOM, a quick intro to DOM

The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web

So basically DOM is a tree structured representation of documents such as XML and HTML. We can use the DOM to add, remove or update elements in those documents.

What is virtual DOM?

Virtual DOM is a representation of the DOM. The creation of real dom will be handled by browsers. Modern frameworks like react, vue, etc.., will create a tree of elements similar to real dom in memory this is called virtual DOM.

For example:

<ul class="fruits">
    <li>Apple</li>
    <li>Orange</li>
    <li>Banana</li>
</ul>

The above code can be represented in the virtual DOM as below.

// Virtual DOM representation
{
  type: "ul",
  props: {
    "class": "fruits"
  },
  children: [
    {
      type: "li",
      props: null,
      children: [
        "Apple"
      ]
    },
    {
      type: "li",
      props: null,
      children: [
        "Orange"
      ]
    },
    {
      type: "li",
      props: null,
      children: [
        "Banana"
      ]
    }
  ]
}

Why do we need virtual DOM?

In earlier days when SPA wasn't much popular, rendering was done on the server-side. So for every user interaction/request, the server will send a new page to render.

In the case of SPA, there will only one document and in that same document, all DOM manipulations will be done. So for complex projects, many unoptimized DOM operations might be used.

For example: Let's say we want to render list from an array. we can do it like below.

function generateList(fruits) {
    let ul = document.createElement('ul');
    document.getElementByClassName('.fruits').appendChild(ul);

    fruits.forEach(function (item) {
        let li = document.createElement('li');
        ul.appendChild(li);
        li.innerHTML += item;
    });

    return ul
}

let fruits = ['Apple', 'Orange', 'Banana']
document.getElementById('#list').innerHtml = generateList(fruits)

Now if the list changes, above method can be called again to generate list.

fruits = ['Pineapple', 'Orange', 'Banana']
document.getElementById('#list').innerHtml = generateList(fruits)

In the above code, a new list is generated and it is set in the document. The problem with this approach is only the text of single fruit is changed but a new list is generated and updated to DOM. This operation is slow in DOM. We can change the unoptimised code like below. This will reduce the number of operations in DOM.

document.querySelector('li').innerText = fruits[0]

The final result of both unoptimized and optimized code is same but the cost of unoptimized DOM operation is performance. If the size of list large then you can see the difference. This was the problem we had in older frameworks like backbone js.

So answer to our big question Why do we need virtual DOM? is to solve the above problem.

What modern frameworks like react does is whenever something is changed in the state/props, a new virtual DOM representation will be created and it will be compared with the previous one. In our example, the only change will be "Apple" to "Pineapple". Since only text is changed instead of replacing whole list react will update the DOM by the following code.

document.querySelector('li').innerText = "Pineapple"

How virtual DOM is faster than real DOM?

No, virtual DOM is not faster than the real DOM. Under the hood virtual DOM also uses real DOM to render the page or content. So there is no way that virtual DOM is faster than real dom.

Then why everyone says virtual DOM is faster? It is not that virtual DOM is faster. By using virtual DOM, we can find out what is changed and with that, we can apply only those changes to real DOM instead of replacing entire DOM.

Is Virtual DOM the only way to reduce costly DOM operations?

Not necessarily, other frameworks like ember js, angular, and svelte uses different approaches to solve the very same problem.

Conclusion

Virtual DOM is a representation of real DOM. Whenever states are changed new virtual DOM will be created and will be compared with previous virtual DOM. And then DOM operations will be applied for those specific changes. The cost of virtual DOM is calculating diff with another virtual DOM. For a big project with lots of components, diff calculation will take time. You can read more about how that is handled here.

Top comments (17)

Collapse
 
rehmatfalcon profile image
Kushal Niroula

While virtual DOM reduces DOM updates, it is also pure overhead as we need to diff at every step.

This is why svelte.dev/ is very exciting. It is not a framework, but a compiler. It will generate the js that will update the DOM directly without needing any diff.

Collapse
 
elevending profile image
Happy_Dog

Like vue1.x? it means every DOM has a watcher instance, when state changed,the deps call the notify method to call all of the watchers to update the dom

Collapse
 
siddharthshyniben profile image
Siddharth

I disagree. Here is an analogy:

Basically, if the browser was your kitchen and your main element a fridge (and your image of the fridge as it would be in five minutes, your virtual DOM), and you bought a lemon, typical render would throw out your fridge, imagine what the fridge with a lemon would look like, buy all the ingredients you had before and also a lemon, then fill the new fridge.

Whereas if you use a VDOM, the VDOM engine figures out that only the lemon has to be added and so only changes that.

If you change only one single element, the change is not not noticeable

Collapse
 
codewithkarthik profile image
Karthik Raja

I am not getting what you disagree.

In this post, I am also explaining the same thing.

What modern frameworks like react does is whenever something is changed in the state/props, a new virtual DOM representation will be created and it will be compared with the previous one. In our example, the only change will be "Apple" to "Pineapple". Since only text is changed instead of replacing whole list.

VDOM figures out which element or part of DOM changed by using reconciliation process and updates only that part.

Collapse
 
siddharthshyniben profile image
Siddharth

I'm sorry I was not clear. I meant I disagree with the fact that VDOM is not faster

Thread Thread
 
codewithkarthik profile image
Karthik Raja • Edited

No, virtual DOM is not faster than the real DOM. Under the hood virtual DOM also uses real DOM to render the page or content. So there is no way that virtual DOM is faster than real dom.

What I meant was you cannot compare apples and oranges. Virtual DOM is not another type of DOM, it is just a representation of DOM. So we should not say Virtual DOM is faster.

React docs state that

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.

Since “virtual DOM” is more of a pattern than a specific technology, people sometimes say it to mean different things.

As you can see above it is a pattern or technique. The reason we should not say that VDOM is faster than actual DOM is because in the end Virtual Dom is going to update the actual DOM.

Thread Thread
 
siddharthshyniben profile image
Siddharth

Yeah, I kind of get your point

Collapse
 
lico profile image
SeongKuk Han

Good explanation :)

Collapse
 
rotimibest profile image
Ibitoye Rotimi Best

Finally someone was able to give a practical example showing why it's *faster.

Thank you.

Collapse
 
shaci profile image
Ivan • Edited

Ok, but what prevents us from just writing this without using virtual DOM?:
document.querySelector('li').innerText = fruits[0]

Collapse
 
rajeshroyal profile image
Rajesh Royal

No worries man, just go and write your own diffing algorithm.

Collapse
 
siddharthshyniben profile image
Siddharth

Simple. We're lazy

Collapse
 
ankitlv profile image
ankitLV

Because you don't know which element got changed beforehand, it could be any.

Collapse
 
hashlucifer profile image
Harsh Mehta • Edited

Very well explain what virtual DOM is, but this doesn't justifies why VirtualDOM is faster because of 2 missing things.

  • When we say that DOM manipulation is slower, its not the Javascript manipulation using document api which is slower, but the process that browser follows after that. Which is layout calculations and pixel painting, every time after every DOM update.

So how does Virtual DOM better? Because everytime you update sometimes in virtualDOM goes the the real DOM, even though you are updating the specific parts of DOM, complexity remains same.
The answer is 2nd point

  • REACT works in batch mode in terms of updating, it updates the virtual DOM every time but updates the realDOM after some time. In this way a bulk of DOM updates goes at once, so the layout calculations and repainting cost gets reduced. In this way Virtual DOM makes things better and faster. This is usually less than 200ms so that our eyes don't comprehend the UI change.
Collapse
 
rmrao12 profile image
rmrao12

okay i read every where about react's virtual dom but i still don't understand like what is the actual difference there while testing react app why testing is not easy cz of this virtual dom someone please clarify this to me i mean if it's using in memory dom than this is an advantage right but why testing becomes difficult as compared to real dom

Collapse
 
rajeshroyal profile image
Rajesh Royal

Finally I understand what the heck is Virtual DOM and why It exists.

Literally from blogs and YT videos what and only I understand was that Virtual DOM is faster and It compare with actual DOM for update that's It.

Thanks again main 👍have a nice day o( ̄▽ ̄)o

Collapse
 
thamaraiselvam profile image
Thamaraiselvam

Finally I am able to understand difference between DOM and Virtual DOM. Thanks man