DEV Community

Tiago Mateus
Tiago Mateus

Posted on

I Finally Understand the Virtual DOM 🤯

Briefly: A user interaction triggers an event. React steps in and creates a new Virtual DOM based on this event. Then, React compares the new Virtual DOM with the previous one (old Virtual DOM). After identifying the differences, React updates the actual DOM, but only for the parts that changed. Yes, that's how it works!

Image description

Yes, I know, it seems more complicated, but it's not! The Virtual DOM that React creates is lightweight, making the process faster.

For example, here is the Virtual DOM representation:

{
  type: "div",
  content: "Hello World!",
  props: { onClick: change }
}
Enter fullscreen mode Exit fullscreen mode

And here is the normal DOM:

<div onClick="change()">Hello World!</div>
Enter fullscreen mode Exit fullscreen mode

See the difference? The Virtual DOM is just a lightweight JavaScript object representing the same structure, while the normal DOM is a heavier, browser-specific implementation.

So, when React makes a diff between the Virtual DOMs (new and old), it's easy! Why? Because it's just a JSON comparison."

Example:

Old Virtual DOM:

{
  type: "div",
  content: "Hello World!",
  props: { onClick: change }
}
Enter fullscreen mode Exit fullscreen mode

New Virtual DOM:

{
  type: "div",
  content: "Hello!",
  props: { onClick: change }
}
Enter fullscreen mode Exit fullscreen mode

React detects the change (the content property) and applies it to the actual DOM. This makes the process efficient, as React avoids updating unnecessary parts of the real DOM.

What do you think about this explanation? Let me know your thoughts or questions in the comments!😁

Top comments (0)