What is the virtual DOM?

The Document Object Model (DOM) is the HTML that you see on a website.

Example:

html
<div id = 'Erik'></div>

Using JavaScript you can manipulate the DOM:

javascript
<script>
function Erik(age){
    
    var h1 = document.createElement("h1")
    var p = document.createElement("p")

    h1.innerHTML = 'Erik'
    p.innerHTML = 'Erik is ' + age + ' years old'

    document.getElementById('Erik').appendChild(p)
    
}

Erik(31)
</script>

In the previous component, we are creating both <h1></h1> and <p></p> components when there is a change in the age of Erik.

Rather than redrawing the whole component, React creates a virtual copy of the DOM, and only updates those pieces whose state has changed.

Example:

jsx
import React from 'react'

const Erik = ({ age }) => {

    return(
        <div id = 'Erik'>
            <h1>Erik</h1>
            <p>Erik's age is {age} years old</p>
        </div>
    )

}

In this example, React will update only {age}, and will not redraw <p></p>. That means, <h1><\h1> and <p></p> remain static.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.