Virtual DOM in react
Published: 2021-05-30 17:16:29

#Why virtual DOM?

To avoid re-creation of elements if possible in real DOM, when one manipulates DOM elements.The Virtual DOM concept can help in efficient DOM manipulation through **diffing** and **reconciliation**.

**Diffing** is a process of comparing the *previous virtual DOM*  to *current virtual DOM* and changing only those elements which are different.

**Note**: *List items should have a *key attribute* to stop recreating the list items that aren't changed.*

**Reconciliation** is when *virtual DOM* syncs with real DOM.

**Real or browser DOM looks like the one shown below:**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x6s4gjs50znlwtqilzil.png)

**Virtual DOM** is representation of UI, like *real DOM* excluding the heavy parts, which is kept in memory as a javascript object.


**Virtual DOM looks like the one shown below:**

``` javascript
//virtual DOM

const virtualDOM = {
    tagName: 'html',
    children: [
      { tagName: 'head' },
      {
        tagName: 'body',
        children: [
          {
            tagName: 'div',
            attributes: { id: 'root' },
            children: [
              {
                tagName: 'div',
                attributes: { class: 'App' },
                children: [
                  {
                    tagName: 'ul',
                    children: [
                      { tagName: 'li', textContent: 'Tea' },
                      { tagName: 'li', textContent: 'Juice' },
                      { tagName: 'li', textContent: 'Water' },
                      { tagName: 'li', textContent: 'Milk' },
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
    ],
  };
```


Suppose there is a list of four items, and you wish to change the *child* of first list item, then in real DOM that *list element will be recreated along with the updated text*.

```javascript
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <script>
      function change() {
        document.getElementById("Tea").innerHTML = "Tee";
      }
    </script>
    <div id="app">
      <ul>
        <li id="Tea">Tea</li>
        <li id="Juice">Juice</li>
        <li id="Water">Water</li>
        <li id="Milk">Milk</li>
      </ul>
      <button id="1" onClick="change()">Change first item</button>
    </div>
  </body>
</html>

```
*The purple highlighted texts in both the images shown below are recreation.*

**Manipulating real DOM without using virtual DOM concept**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dnp9j4q7fkt1xnz5u4vy.png)

```javascript
import React from "react";

export default function App() {
  const [name, setName] = React.useState("Tea");
  return (
    <div className="App">
      <ul>
      
        <li key="Tea">{name}</li>
        <li key="Juice">Juice</li>
        <li key="Water">Water</li>
        <li key="Milk">Milk</li>

    </ul>
      <button id="1" onClick={() => {
        setName("Tee")
      }}>Change first item</button>
    </div>
  );
}

```
If the same thing is done using virtual DOM only the changed *child* not the *list* element will be recreated in the real DOM as shown below.

**Manipulating real DOM using virtual DOM concept**

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x7sf64k5sdbsutfu9v7v.png)