DEV Community

Amr Guaily
Amr Guaily

Posted on

DOM vs Virtual DOM

⏩ What is DOM❓

  • DOM stands for => Document Object Modal

  • DOM is a Programming Interface for the HTML document that allows us to create, change, add, or remove elements from the HTML document.

  • DOM is represented as a tree data structure.

DOM tree


🤔 At this point you may be wondering, and ask yourself Why can't update HTML document directly.. Why DOM is Required ❗❓
✅ We need DOM because JS doesn't natively understand HTML document. So the browser creates DOM. therefore we could say that DOM is an API that represents the same HTML document but in different format (object format).
For example: JS can't understand the <h1></h1> tag in HTML documents ,it only understand h1 object in DOM.

Updating DOM is Expensive, WHY ❗❓

✅ Whenever DOM changes it causes browser to run two expensive operations: Reflow and Repaint


Because of how updating DOM is expensive - React is using Virtual DOM.

⏩ What is Virtual DOM❓

React uses virtual DOM which is a lightweight copy of the actual DOM, the only difference is the ability to directly change the layout of the document.

How DOM updates in React❓

  • On the first run, both virtual DOM and real DOM are created.

  • Whenever state changes:

    • React creates a new virtual Dom and compare it with the previous one.
    • The compression is done by Diffing Algorithm.
    • After compering react creates a new virtual Dom with the changes.
    • Then React updates the real DOM without rendering the entire DOM, and this is how virtual DOM is helping to enhance performance.
  • This entire process of transforming changes to the real DOM is called Reconciliation.

🤔 Suppose we have new data similar to the previous one?

✅ In that case React compares previous and new structures and sees that it has no change, so nothing gets rendered to the Browser. This is how the Virtual DOM is helping to enhance the Browser performance.

🤔 Is Virtual DOM the only way to reduce costly DOM operations?

✅ Not necessarily, other frameworks like ember.js, angular, and svelte uses different approaches to solve the very same problem.


⏩ Recap:

DOM vs Virtual DOM


⏩ Learn Further:

https://www.geeksforgeeks.org/reactjs-virtual-dom/
https://dev.to/gopal1996/understanding-reflow-and-repaint-in-the-browser-1jbg
https://www.geeksforgeeks.org/reactjs-reconciliation/

Top comments (0)