DEV Community

Cover image for Why Virtual DOM: Render and Performance
Sonay Kara
Sonay Kara

Posted on • Edited on

Why Virtual DOM: Render and Performance

In this article, we will examine the dom in detail and what the virtual dom is.


What is the DOM (Document Objec Model) ?

When a web page is loaded into the browser, the browser generates HTML to display the requested page to . This html structure is like a tree. DOM is formed as a result of converting the content of a web document (HTML or XML) into an object-oriented structure by the browser.Thanks to this structure, the page content is organized in a tree structure in the browser, and each HTML tag or content is represented as a "node".


Now explore the document object model :

Let's write an example code to access the document object.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document object model</title>
</head>
<body>
    <div class="card" style="width: 18rem;">
        <img class="card-img-top"  alt="Card image cap">
        <div class="card-body">
          <h5 class="card-title">Lorem, ipsum dolor.</h5>
          <p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Hic, tenetur!</p>
          <a href="#" class="btn btn-primary">Lorem, ipsum.</a>
        </div>
      </div>


    <script src="/script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
console.log(document)
Enter fullscreen mode Exit fullscreen mode

Output :

Image description


We can access the dom with console.log(document). When we examine the Document object, we understand that this object represents an HTML document. In other words, the document object contains all the tags in an HTML document.

With Javascript, we can access the tags inside the document object and manipulate the tags inside this document object to create dynamic web pages. Let's give an example of how to access :

const wrapper = document.getElementById("card")

console.log(wrapper)
Enter fullscreen mode Exit fullscreen mode

Output:

Image description


What is the Virtual DOM?

Image description

We now know that the easiest way to change the dom ("Change HTML") is to change the innerHTML property in an element. This method of modifying html does not performance well in DOM repainting (" Updating what the user sees ").This is because innerHTML needs to parse DOM nodes from a string, preprocess, and append it. if there are too many html mutations on a web page, there will be a performance issue.

So how were the performance issue fixed ?

This problem was fixed by creating a virtual DOM. The virtual DOM is a copy of the real DOM stored in memory. When the user interacts with the web page and the state of the web page is updated, a new virtual DOM is created in memory. This new virtual DOM is compared to the previous virtual DOM to identify changes, and these changes are applied to the real DOM to be shown to the user.

This is the working logic of the modern libraries you use and uses the dif algorithm for comparison. they all use virtual DOM. But although the virtual DOM approach is fast, there are points that need to be considered for performance. A change in the virtual domain renders the entire web page Libraries have hooks for performance optimizations

Conclusion

in this article, we have examined what dom and virtual DOM are. We found out why virtual dom is used. Now you know what dom and virtual dom are.

Top comments (14)

Collapse
 
itsakza profile image
akzaisme

Ya. "Modern" libraries are moving away from Virtual DOM because when you're doing SSR on server side, this just slows down the entire process and make the application unnecessarily heavy and bloated making developer experience worse. When you're sending only partial components with SSR, calculating such complex DOMs becomes overkill. That's why strategies like Svelte or SvelteKit gained popularity because compilers knows how to render that Component and does it even needs to be executed ahead of time and can it be cached etc. While Virtual DOM has to be memoized. React team is switching to a hybrid compiler model but they can't go full compiler like Svelte and Solid does because of library complexity.

Collapse
 
sonaykara profile image
Sonay Kara

You are right, I will explain srr and csr in another article

Collapse
 
lexlohr profile image
Alex Lohr

The virtual DOM is based on the misconception that it is not possible to know in advance which state changes will lead to what DOM changes.

Nearly all modern frameworks but React are now based on signals, which bind state changes directly to render effects.

Collapse
 
quanla profile image
Quan Le

You should have mentioned that the structure of the virtual dom tree is different from the browser dom tree. Since virtual dom tree has nodes for Component, Fragment, Empty (true, false, null...) Context... and browser tree does not. People dont know that, but I guess they dont care

Collapse
 
sonaykara profile image
Sonay Kara

You're right! It's a great point that the virtual DOM tree has a different structure, with nodes for Components, Fragments, Empty values, and Context, unlike the browser DOM.

Collapse
 
mayukh_chakraborty_3ec951 profile image
Mayukh Chakraborty

Well there are going to be a few corrections:

  1. Using .innerHTML is actually much faster than creating bunch of nodes via .createElement

This is primarily because web browsers are optimized to process strings that we call HTML, and also, the entire processing and node creation part is handled by native code, so it's observably faster than manual creation.

  1. VDOM was not really created because of perceived slowness of .innerHTML, rather it hints to a limitation of the web, where we can clearly see that the browser don't diff the nodes itself for some reason. Also it was considered faster before signal architecture became popular.

  2. Ultimately, any imperative javascript code will outperform frameworks any day. (Ofcourse given that it's well written)

Collapse
 
sonaykara profile image
Sonay Kara

Hi Mayyukh,

1-This maybe true, but I did not say otherwise in this article.
2- in this article, I did not say that vdom was created because innetHtml is slow. what I want to analyze is : "VDOM usually works faster than manual DOM manipulations done directly with JavaScript to change something in the browser. This is because VDOM calculates changes to a virtual DOM structure using a diff algorithm and applies only the necessary updates to the real DOM. "

Read this section again
We now know that the easiest way to change the dom ("Change HTML") is to change the innerHTML property in an element. This method of modifying html does not performance well in DOM repainting (" Updating what the user sees ").This is because innerHTML needs to parse DOM nodes from a string, preprocess, and append it. if there are too many html mutations on a web page, there will be a performance issue.

3- Performance and code writing/editing are different concepts. frameworks and libraries provide developers with ease of writing code, reusability, and performance optimization with technologies such as VDOM. For example, libraries such as React make it easier for developers to write more sustainable and readable code.

It may be useful to examine the term "JSX" at this point. JSX allows you to use an HTML-like syntax within JavaScript code and makes it easier to define and edit components in libraries such as React. JSX is compiled into JavaScript and interacts with VDOM, efficiently updating user interfaces. you can also explore the concepts of server side rendering and client side rendering

Collapse
 
rafiyuddin_shaikh_87dec3f profile image
Rafiyuddin Shaikh

Virtual dom is used only in react or other api

Collapse
 
sonaykara profile image
Sonay Kara

react.js , vue.js ,preact, etc.

Collapse
 
sirajulm profile image
Sirajul Muneer

Most frameworks now move away from virtual dom, and can perform way better than react.

Collapse
 
erickrodrcodes profile image
Erick Rodriguez

Nice explanation on why many frameworks and libraries uses virtual DOM. Thanks! Keep the good content.

Collapse
 
sonaykara profile image
Sonay Kara

Thanks a lot Erick

Collapse
 
tejavsk_namuduri_05aa01ce profile image
tejavsk namuduri

The virtual DOM (VDOM) is a performance-boosting mechanism used by frameworks like React to optimize updates in the actual DOM. By creating a lightweight copy of the real DOM, the VDOM reduces the number of direct DOM manipulations, which are known to be slow. Here's how it works and some alternatives that can potentially offer even better efficiency:

How the Virtual DOM Improves Performance

  1. Minimized Re-renders: When a component’s state changes, the virtual DOM calculates changes in a virtual representation before updating the real DOM. This reduces unnecessary re-renders.
  2. Efficient Diffing Algorithm: The VDOM uses a diffing algorithm to identify exact changes between the current and previous VDOM states, only updating parts of the actual DOM that changed.
  3. Batch Updates: VDOM frameworks like React batch updates together, reducing the number of real DOM manipulations and improving efficiency.
  4. Reduces Layout Thrashing: By minimizing direct DOM access, the VDOM helps avoid frequent reflow and repaint cycles, making it beneficial for complex or interactive applications.

Alternatives to the Virtual DOM

  1. Reactive DOM (e.g., Svelte): Svelte doesn’t use a virtual DOM. Instead, it compiles components to direct JavaScript code at build time, updating the real DOM instantly based on state changes. This often results in faster performance than the VDOM because it avoids the diffing and VDOM re-rendering process.

  2. Incremental DOM (e.g., Google’s Lit): Incremental DOM updates only specific parts of the DOM that have changed, without needing a virtual DOM tree. This can be more memory-efficient and is beneficial for lightweight applications with simpler UI components.

  3. Fine-grained Reactivity (e.g., Solid.js): Fine-grained reactivity, as seen in Solid.js, directly links state to specific parts of the DOM. This avoids the need for a VDOM by updating only what’s necessary, allowing for faster, more granular updates, especially in interactive applications.

  4. Direct DOM Manipulation (Vanilla JavaScript or jQuery): Direct manipulation is suitable for simpler applications with few state changes. While efficient for straightforward UIs, it can become challenging and less performant in state-heavy applications due to the lack of controlled rendering.

Are These Alternatives More Efficient?

In some scenarios, these alternatives can indeed be more efficient than the virtual DOM:

  • Svelte’s compile-time optimizations and Solid’s fine-grained reactivity skip the VDOM diffing process, which can lead to faster and more memory-efficient updates.
  • Incremental DOM avoids the overhead of a VDOM, making it effective for lightweight UIs.

However, the virtual DOM remains effective for complex applications with frequent updates and nested structures. Choosing the best approach depends on the application’s complexity and performance needs, as each method has its strengths for different use cases.

Collapse
 
msegmx profile image
msegmx

Which one did you use to "write" this answer: chatgpt, copilot, google, claude..? 🙄