The Key 🔑 Concept of Responsive Interfaces in ReactJS
Tags: webdev, react, performance, frontend
Published: 2023-10-02 15:58:06

## What is the Virtual DOM?

Well, it’s a representation of the actual DOM, stored and synchronized with it by React through its ReactDOM library.

In case you briefly know what the DOM is, or not, imagine that when a web page (web document 📄 ) loads in a browser, it generates a kind of tree-like data structure of the page. 
This structure is in the form of nodes and objects used to store information about the various elements (more precisely, the tags) on the page. 
These objects can represent windows, documents, sentences, or even styles. The generated structure is thus called the DOM (Document Object Model). 
The information in this DOM can then be read and modified smoothly by scripting languages like JavaScript with the help of libraries such as React.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kwtyy6t83womekmlz2c4.gif)

## Why Create a Virtual DOM ?

The virtual DOM was created primarily for **optimization** reasons, let me explain.

When a modification is made to a web page, the browser updates loops the part of the page affected by that modification and redraws it.

The problem is that for all modifications, no matter how small they are, the browser performs a new analysis and a new rendering. When many modifications are made frequently, it becomes a whole different story 🔥.

To optimize these sometimes excessive updates, several approaches are used, including the **[VDOM (Virtual DOM)](https://fr.legacy.reactjs.org/docs/faq-internals.html)**, **[lazy loading](https://en.wikipedia.org/wiki/Lazy_loading)**, **[throttling](https://en.wikipedia.org/wiki/Bandwidth_throttling)** and **[debouncing](https://www.notion.so/Api-request-in-vanilla-Javascript-119c77f793764161ae2741eb25374015?pvs=21)**, as well as libraries like **[Redux](https://redux.js.org/)**.

## How Does React Use the VDOM?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibjtgcuz45q7v1fwc720.png)

During the initial rendering of the application, React creates a tree of the virtual DOM for the web page and stores it in memory.

1. When the application is updated (with each **`setState()`** call or prop change), React creates a new VDOM tree with all the modifications.
2. It detects the elements that have changed and those that need to be updated by comparing the new VDOM tree with the previous one, using a diffing algorithm called "Reconciliation."
3. From this, it generates an action plan that details the updates to apply to the actual DOM.
4. Finally, React applies the necessary updates to the real DOM, following the action plan generated with ReactDOM.

> 💡  **But how does React manage DOM changes differently from direct manipulation in pure JavaScript?**

> When you make multiple rapid changes to the DOM in pure JavaScript, each change can trigger an immediate update, while React has the ability to group these changes to apply them all at once, thereby avoiding excessive operations.


## Going Further 🔎: What Does This Comparison Algorithm Do?

As you might expect, React compares elements of the virtual DOM from the root node to the last node and acts differently depending on the types of elements.

### Change of Type

When an element changes its type (for example, from **`<a>`** to **`<button>`**), React destroys the current tree and creates a new one by inserting the new elements.

For example, by comparing these two elements:

```html
<!-- Initial State -->
<div>
    <a href="javascript:void(0)">Like</a>
</div>

<!-- State After Modification -->
<div>
    <button>Like</button>
</div>
```

React rebuilds the entire VDOM by replacing the **`<a>`** node with the **`<button>`** node.

### Property Change

However, when it's just a property change, React only updates the property in the VDOM.

```html
<!-- Initial State -->
<div className="card"></div>

<!-- State After Modification -->
<div className="card card__white"></div>
```

No comment.

### Handling Children

Let's imagine two **`<ul>`** lists:

```html
<!-- Old List -->
<ul>
  <li>Cat</li>
  <li>Dog</li>
</ul>

<!-- New List with Addition -->
<ul>
  <li>Cat</li>
  <li>Dog</li>
  <li>Bird</li>
</ul>
```

By comparing each element in these lists, React notes that the element **`<li>Bird</li>`** has been added by correspondence and simply updates it.

But, but, but if you add an element to the beginning:

```html
<!-- Old List -->
<ul>
  <li>Cat</li>
  <li>Dog</li>
</ul>

<!-- New List with Addition at the Beginning -->
<ul>
	<li>Bird</li>
  <li>Cat</li>
  <li>Dog</li>
</ul>
```

When comparing the first children **`<li>Cat</li>`** and **`<li>Bird</li>`**, React considers this a change of type. It will update each element individually (which is not ideal for performance).

This is where React's **`key`** attribute comes into play. It uses it to match the children of the initial tree with those of the subsequent tree.

```html
<!-- Old List -->
<ul>
  <li key="1">Dog</li>
  <li key="2">Cat</li>
</ul>

<!-- New List with KEY -->
<ul>
  <li key="3">Bird</li>
  <li key="1">Dog</li>
  <li key="2">Cat</li>
</ul>
```

Now, React knows that the element with key '3' is new, and the elements with keys '1' and '2' have been moved. Thus, React can efficiently rearrange the elements without having to rebuild the entire list.

---

In summary, ReactJS stands out as a tool of choice for creating user interfaces. With the virtual DOM explained here, React optimizes performance by minimizing costly updates to the real DOM, contributing to smooth interfaces and efficient development. It is worth noting that while React is recognized for this approach, it is not the only one to adopt it.

If you have any questions or would like to learn more about, feel free to reach out.