What is virtual DOM ?

  • 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.

[pastacode lang=”markup” manual=”%3C!doctype%20html%3E%0A%3Chtml%20lang%3D%22en%22%3E%0A%20%3Chead%3E%3C%2Fhead%3E%0A%0A%20%3Cbody%3E%0A%20%20%20%20%3Cul%20class%3D%22list%22%3E%0A%20%20%20%20%20%20%20%20%3Cli%20class%3D%22list__item%22%3EList%20item%3C%2Fli%3E%0A%20%20%20%20%3C%2Ful%3E%0A%20%20%3C%2Fbody%3E%0A%3C%2Fhtml%3E%0A” message=”” highlight=”” provider=”manual”/]

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.

[pastacode lang=”markup” manual=”const%20listItemOne%20%3D%20document.getElementsByClassName(%22list__item%22)%5B0%5D%3B%0AlistItemOne.textContent%20%3D%20%22List%20item%20one%22%3B%0A%0Aconst%20list%20%3D%20document.getElementsByClassName(%22list%22)%5B0%5D%3B%0Aconst%20listItemTwo%20%3D%20document.createElement(%22li%22)%3B%0AlistItemTwo.classList.add(%22list__item%22)%3B%0AlistItemTwo.textContent%20%3D%20%22List%20item%20two%22%3B%0Alist.appendChild(listItemTwo)%3B%0A” message=”” highlight=”” provider=”manual”/]
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like

What is Prop Drilling ?

We pass a prop with another component with the help of all the components that come between, this method is known as prop drilling. Prop drilling is basically a situation…
View Answer

What is React DOM ?

It is an object which exposes a number of top level APIs to interact with the browser DOM. It provides DOM-specific methods that can be used at the top level…
View Answer

What is Flux ?

It is an application architecture that Facebook makes use of internally for constructing the client-side web application with React . It is a programming concept, where the data is a…
View Answer