DEV Community

Cover image for ReactJS: What is the Virtual DOM?
Adriana DiPietro
Adriana DiPietro

Posted on

ReactJS: What is the Virtual DOM?

Questions

Today, I will be talking through the Virtual DOM through the structure of the questions to follow:

  1. What is the DOM?
  2. What is the Virtual DOM?
  3. Why do we use the Virtual DOM? How does the Virtual DOM apply to ReactJS?

☁️ Let's get started ☁️

What is the DOM?

We should probably start at the beginning.

(1)The DOM, short for "Document Object Model", is a data representation of the structure and content of a document in the browser.
(2)The DOM is comprised of objects.

As it represents a browser's document and is comprised of objects, it can be manipulated using scripting languages, such as JavaScript.

An example of a DOM may look like this:

<html>
   <body>
      <div class="welcome-page">
        <h1>Welcome!</h1>
        <p>My name is Adriana</p>
      </div>
   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The DOM manipulates the content, specifically HTML elements, into a tree-like formation 🌲!

We can access the DOM of a webpage by right clicking on the page and clicking "inspect". This prompts the "Elements" tab to be opened either on the side or bottom of the page. And here is where you can see any DOM tree of any website.

Here is an example from Google's homepage:

Screen Shot 2021-08-17 at 7.28.29 PM

In the bottom left corner, we can see Google's homepage DOM tree. While we may not understand all of it, we can point out some key features that resemble my example from above:

<html> tag with its closing tag </html>

<body> tag with its closing tag </body>

<div> tag with its closing tag </div>

Inside each of these DOM elements holds code that helps to render what we see on the Google homepage: the colorful Google logo, the search bar, the Google Search button... etc.

So, ultimately, the DOM helps to convert a scripting language like JavaScript or ReactJS into renderable content that a user can see on a webpage.

What is the Virtual DOM?

Now we know what the DOM is, we can talk about the Virtual DOM. Given to us from a React library called "ReactDOM", the Virtual DOM is a representation of the DOM! (Whoa, so meta!)

Why do we use the Virtual DOM? How does it apply to ReactJS?

We use the Virtual DOM with ReactJS as to be more efficient. When updating or modifying code that will be rendered to the (real) DOM, ReactJS takes a look at both DOMs and compares. When ReactJS sees that only some of the content has changed, it implements only those changes to the DOM. Comparing the DOMs avoids having to do a huge rerender of all of the content. This would take time and a lot of power. And we are all about being efficient here.

Let's look at some examples:

This is the DOM "right now" ⤵️

<html>
   <body>
      <div class="welcome-page">
        <h1>Welcome!</h1>
        <p>My name is Adriana</p>
      </div>
   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now, I've decided to add another "p" tag ⤵️

<html>
   <body>
      <div class="welcome-page">
        <h1>Welcome!</h1>
        <p>My name is Adriana</p>
        <p>I am 1000 years old</p>
      </div>
   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

ReactJS will see this change and rerender every single element to the Virtual DOM, whether it is new or not. Once the Virtual DOM is fully updated, then ReactJS will compare it to the DOM. ReactJS will render what has changed to the DOM; it will NOT rerender the whole DOM tree!

In Summary

  1. The DOM is rendered.
  2. A change occurs.
  3. The change is reflected in the Virtual DOM.
  4. The entire Virtual DOM gets updated.
  5. ReactJS compares the Virtual DOM to the DOM.
  6. React sees what has changed; only those elements get updated onto the (real) DOM.
  7. The changes on the DOM are seen in the browser.

☁️Thank you for reading along!☁️
💬Comment below to continue the discussion💬
💭Ask me some questions💭

Top comments (9)

Collapse
 
marzelin profile image
Marc Ziel

DOM is a web API that allows a programmer to interact with the rendered document from JavaScript.

Virtual DOM isn't a proper name, the proper name is React Element Tree. It's a structure that describes the view. The view can be an html document, a native app UI or anything else. React Element Tree is an abstract structure that allows to render practically anywhere (you just need a custom renderer for a given output). In the case of the web it's kind of simplified DOM representation and it had been called Virtual DOM before facebook introduced React Native, the times when React could only render to a web document.

Efficiency isn't the only reason why 'VDOM' is used. The second reason (probably more important since modern machines and browser engines are powerful enough to rerender the whole page really fast) is that DOM is stateful so your input or scroll position would be discarded on rerender.

React doesn't compare 'VDOM' to DOM, it compares existing 'VDOM' with a newly generated 'VDOM' in a process called reconciliation which produces a sequence of patches that needs to be applied by a renderer to make the view in sync with the current 'VDOM'.

Collapse
 
trunghieu99tt profile image
Trung Hieu Nguyen

Hmm, can you specify more about the Efficiency of "VDOM" ? I know that it' would be faster for searching and updating on "VDOM", but the point here is, after updating VDOM, we still have to update the Real DOM. As far as I know, updating Real DOM is pretty fast too, the thing slows down Real DOM is that it has to re-calculate layout, css, do something called "repaint" (I don't really remember what's called). So instead of: update component -> update Real DOM, now with VDOM: update component -> update VDOM -> update real DOM. So what makes VDOM more efficient?

Collapse
 
marzelin profile image
Marc Ziel • Edited

The thing is that you can't do: update component -> update Real DOM because there isn't an automatic update method on the DOM. You (or React in this case) have to manually figure out what properties / elements have changed and update them one by one. How can you figure out what changed? By comparing current and desired React Element Tree (VDOM).

However, update component -> update Real DOM is possible with a compilation step. A compiler can detect which parts of the tree are static and which are dynamic, figure out the relations between state change and view change and generate code that precisely updates desired properties so there's mostly no need for diffing at runtime. That's the reason why svelte and the like are much faster than React (solidjs takes things even further and also takes components out of the equation at runtime so there's just state update -> DOM update and the code is nearly as fast as vanilla js).

Thread Thread
 
trunghieu99tt profile image
Trung Hieu Nguyen

As you said, we still have a way to update component then update RDOM but React doesn't use it so it has to use VDOM to help to deal with figuring changes and updating RDOM. If it's true, VDOM is not really efficient, it's just a "must have" thing to make React work the right way ?

Thread Thread
 
maxkoretskyi profile image
Max • Edited

If it's true, VDOM is not really efficient, it's just a "must have" thing to make React work the right way ?

The short answer is yes. It's just a way to detect changes and synchronize component's state to the DOM.

All web frameworks today define and work with abstractions (objects) that describe real DOM e.g. Fiber in React, LView in Angular. @marzelin is right that if you have a compilation step, say like in Angular or Svelte, you can identify dynamic parts and only check their values and perform isolated updates if needed. This approach is faster that comparing entire trees, like in React. On the hand, React allows very dynamic tree modifications in runtime, while with the compilation step all dynamic behavior needs to be known at the compilation stage. Also, React doesn't need custom syntax for that, while Angular has a mechanism of directives to mark dynamic behavior in HTML templates.

I've written extensively about this topic in these two articles:

Thread Thread
 
marzelin profile image
Marc Ziel

Having this abstract description of a view allows you to reuse code. Technically, you can take a source code for a component and use it to render to both a web app and a native app by just switching the renderer from react-dom to react-native.

Compile-time optimizations were promised with the introduction of hooks. A small step was already made with the new JSX transform.

At the moment React team is busy working on a concurrent mode which is a different approach to improving performance. Instead of optimizing rendering itself you slice the work into small pieces that are executed asynchronously so that user interactions (typing, clicking, scrolling) are never blocked even if there's a lot to rerender so the app seems fast and responsive.

Collapse
 
am20dipi profile image
Adriana DiPietro

Thank you Marcin for your input! Much appreciated!

Collapse
 
prineth profile image
Prineth Fernando

Short and sweet. Love it.

Collapse
 
am20dipi profile image
Adriana DiPietro

Thanks for your comment!