What is Virtual DOM?

February 1, 2023

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

What is Virtual DOM?

Virtual DOM is a programming concept that is used not only in React but also in other frameworks such as Vue. However, this article will focus on React's Virtual DOM. Virtual DOM is stored in memory as a JavaScript object, simulating the real DOM.

Is Virtual DOM faster than directly manipulating the DOM?

Many people believe that the advantage of using Virtual DOM is that it is more efficient and faster than directly manipulating the DOM. However, this idea is not entirely correct. React official has never claimed that Virtual DOM is faster than directly manipulating the DOM. On the contrary, using Virtual DOM is usually slower than native DOM operations because of the extra layer of operation.

So, why use Virtual DOM?

Advantages of React Virtual DOM

According to the React official documentation, the advantage of using Virtual DOM is that: this approach enables the declarative API of React. In other words, this means that we do not need to directly manipulate the DOM, but rather through a declarative syntax. The declarative writing style allows developers to tell React what UI we want through state, without having to directly manipulate the DOM. React ensures that the DOM and the state match.

Declarative writing style can avoid the following two problems with direct DOM manipulation:

  1. When the DOM Tree structure becomes larger, it becomes difficult to manage. For example, there is now a large form component, and when changing a value, it may be necessary to traverse all the form component nodes and operate the DOM to change the value, which can easily result in unnoticed bugs during this process.
  2. Low efficiency. Although DOM operations may be fast, during rendering and reflow stages, frequent direct DOM operations are often the main cause of frame stuttering, so the more you directly manipulate the DOM, the more likely you are to hit performance bottlenecks.

By using Virtual DOM, developers can focus only on the UI without worrying about how to implement it. During the rendering process, React will automatically compare the Virtual DOM and the real DOM, making only the necessary changes to the real DOM.

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee