• It is a lightweight JS object which is an in-memory representation of real DOM.
  • It 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.
  • Virtual DOM has the same properties as that of the Real DOM, however it lacks the power to directly change the content of the screen.
  • It is also considered as a part of “virtual DOM” implementation in React.
  • Although the concept has been around for several years, it was made more popular by its use in the React framework.
  • It is Created by “Richie Harris”.

Why do we need a virtual DOM ?

  • In our client-side application has a super complex structure, which will result in a complicated DOM tree.
  • Manipulating DOM at once can without problems result in overall performance.

For example, let’s take this simple HTML document with an unordered list one list item.

<!doctype html>
<html lang="en">
<head></head>

<body>
<ul class="list">
<li class="list__item">List item</li>
</ul>
</body>
</html>

This document can be represented as the following DOM tree.

We need to adjust the content of the first list item to “List item one” and also add a 2nd listing object. we will need use the DOM APIs to find the elements we need to replace, create the new elements, upload attributes and content, then finally replace the DOM elements themselves.

const listItemOne = document.getElementsByClassName("list__item")[0];
listItemOne.textContent = "List item one";

const list = document.getElementsByClassName("list")[0];
const listItemTwo = document.createElement("li");
listItemTwo.classList.add("list__item");
listItemTwo.textContent = "List item two";
list.appendChild(listItemTwo);

Categorized in: