Why do we need Virtual DOM?

I read the article https://dev.to/karthikraja34/what-is-virtual-dom-and-why-is-it-faster-14p9

There is example of code, example must help us to understand answer on the question – "Why do we need virtual DOM?"

From article:

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');

  fruits.forEach(function (item) {
    let li = document.createElement('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"

Ok, i understad the purpose of Virtual DOM –

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

But what prevents us from just writing this without using virtual DOM?

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

58 thoughts on “Why do we need Virtual DOM?”