What is a virtual Dom? And why is it faster?

According to React docs, the virtual DOM is

fictitious DOM(VDOM)Is a programming concept in which UI Ideal or "virtual" representations of the ReactDOM Libraries like this and "real" DOM synchronization

Before delving into virtual DOM, give a quick introduction to it

Document object model ( DOM)Is the data representation of the object, including Web Structure and content of the document above

Therefore, DOM is basically a tree representation of documents such as XML and HTML. We can use DOM to add, delete, or update elements in those documents.
What is a virtual DOM?

A virtual DOM is a representation of a DOM. The creation of the actual DOM is handled by the browser. Modern frameworks, such as react, vue, and so on, create element trees in memory that resemble real doms, called virtual DOMs.

For example:

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

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

{
  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 a virtual DOM?

In the early days when SPA was less popular, rendering was done on the server side. Therefore, for each user interaction/request, the server will send a new page for rendering.

For SPA, there will be only one document, and all DOM operations will be completed in the same document. Therefore, for complex projects, many DOM operations may be used that are not optimized.

For example: suppose we want to render a list from an array. We can look like this

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, you can call the above method again to generate the list.

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

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

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

Unoptimized and optimized code end up with the same results, but the cost of an unoptimized DOM operation is performance. If the list size is large, you can see the difference. This is the problem we encountered in earlier frameworks such as the backbone js.

So to answer our big question, why do we need a virtual DOM? Is to solve the above problems.

What modern frameworks like react do is create a new virtual DOM representation and compare it to the previous one whenever the state/property changes. In our example, the only change is to change "Apple" to "Pineapple". Since only the text is changed instead of replacing the entire list, react updates the DOM with the following code.

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

How can a virtual DOM be faster than a real DOM?

No, virtual DOM will not be faster than real DOM. Internally, virtual DOMs also use real DOMs to render pages or content. Therefore, a virtual DOM cannot be faster than a real one.

So why does everyone say virtual DOM is faster? Not that virtual DOM is faster. By using a virtual DOM, we can find out what has changed, and we can apply changes only to the real DOM without replacing the entire DOM.
Is virtual DOM the only way to reduce expensive DOM operations?

Not necessarily, other frameworks, such as ember js, angular, and svelte, use different methods to solve the same problem.
conclusion

A virtual DOM is a representation of a real DOM. Whenever the state changes, a new virtual DOM is created and compared with the previous virtual DOM. The DOM action will then be applied to those specific changes. The cost of a virtual DOM is to calculate the difference from another virtual DOM. For large projects with many components, the difference calculation will take time. Here you can learn more about how to handle it.

Translations from
https://dev.to/karthikraja34/what-is-virtual-dom-and-why-is-it-faster-14p9

Keywords: React

Added by Paingiver on Mon, 07 Mar 2022 20:01:25 +0200