Skip to content
CodeWithKarthik

What is Virtual Dom? And Why is it faster?

2 min read

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:

1<ul class="fruits">
2 <li>Apple</li>
3 <li>Orange</li>
4 <li>Banana</li>
5</ul>

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

1// Virtual DOM representation
2{
3 type: "ul",
4 props: {
5 "class": "fruits"
6 },
7 children: [
8 {
9 type: "li",
10 props: null,
11 children: [
12 "Apple"
13 ]
14 },
15 {
16 type: "li",
17 props: null,
18 children: [
19 "Orange"
20 ]
21 },
22 {
23 type: "li",
24 props: null,
25 children: [
26 "Banana"
27 ]
28 }
29 ]
30}

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.

1function generateList(fruits) {
2 let ul = document.createElement('ul');
3 document.getElementByClassName('.fruits').appendChild(ul);
4
5 fruits.forEach(function (item) {
6 let li = document.createElement('li');
7 ul.appendChild(li);
8 li.innerHTML += item;
9 });
10
11 return ul;
12}
13
14let fruits = ['Apple', 'Orange', 'Banana'];
15document.getElementById('#list').innerHtml = generateList(fruits);

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

1fruits = ['Pineapple', 'Orange', 'Banana'];
2document.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.

1document.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.

1document.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.

© 2021 by CodeWithKarthik. All rights reserved.
Theme by LekoArts