DEV Community

José Lázaro
José Lázaro

Posted on

Understand React and Virtual DOM (easy explanation)

Every time we talk about React and its main benefits, we encounter the term Virtual DOM, a very cool feature that makes React an awesome option for building applications.

What DOM is?

Before understanding what the Virtual DOM is, let's first take a look at the REAL DOM.

DOM stands for Document Object Model. It is essentially a structure that represents all the elements in the HTML of a page.

Image description

Each element in this tree structure is a node. Nodes can have children, meaning each element can have its own subtree as well.

<div>
  <p>Some Text</p>
</div>
Enter fullscreen mode Exit fullscreen mode

The example above shows a div node that has a p node as its child. The simplest way to explain what the DOM is: A tree structure representing the relationships between HTML elements.

In a traditional web application (think of older web pages you might have used), updating an element on the screen often meant reloading the entire page. This default approach could become cumbersome, especially in large applications with frequent updates.

The Virtual DOM provides a more efficient way to manage state and data in an application without needing to reload the entire page to apply changes.

How does it work?

React creates an in-memory representation of the real DOM called the Virtual DOM. This representation is constantly observed by React 👀.

Whenever the user interacts with the application, React compares the updated Virtual DOM with the previous version of the real DOM using a process called "Diffing."

If React detects a change, it identifies the exact node where the change occurred and updates only that part of the DOM. This avoids refreshing the entire page and results in a much smoother user experience. So smart!!!1

Some potential challengers

For highly dynamic applications, such as those with real-time updates (e.g., graphs or games), the Diffing process might become slow because React needs to evaluate every change. This can impact performance.

Furthermore, managing large lists can be a very big challenge if not handled properly. For example, when the state of a large list changes, React might need to reconcile many DOM updates, leading to laggy performance.

To mitigate this, React uses key properties in lists. These keys help React uniquely identify each item in the list and efficiently determine which items were added, removed, or updated.

Image description

Thats the basic you need to know about Virtual DOM. You can check more details in reference section or googling a little bit more. Feel free leave any questions in the comments. See you soon.

References

W3 explanation about DOM
React documentation about Virtual DOM
Free Code Camp Virtual DOM article

Top comments (0)