React: how I understand Virtual DOM through useState
Tags: beginners, react, javascript, webdev
Published: 2023-10-11 06:54:29

Honestly. Due to the pressure of ✨ getting things done ✨ while working on my class project using React, all I knew about state in React is simply as a tool in managing data at a component level. And I used to be that _using framework due to rising popularity_ kind of programmer.

But come on, don't lie. Sometimes some of you are still like this right?

![Hehehe](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ya9oanj1ep8hxeacv9c.png)

But of course, I'm not (or should I say, _trying not to be_) like that anymore which is why I'm writing this hahaha. Ok enough with the intermezzo. Let's get into this, shall we?

## Table of Contents

- [Component Scoping](#component-scoping)
- [Virtual DOM](#virtual-dom)
- [Further Readings](#further-readings)

## Component Scoping
The thing about React is that it incorporates the 'scoping' mindset using component so well. So well that I forgot that **React is still built on top of our sweet old HTML + JavaScript with DOM**.

Since I have learned about OOP (Object Oriented Programming) first before React, I see component as a resemblance of object encapsulation where changes will only affect particular component.

Perhaps if you're not familiar with OOP or you didn't get my point, let me give the analogy. Your house consists of several rooms right? There's bedroom, kitchen, etc. If you want <u>only</u> your bedroom to be painted blue, it should be possible right? Not necessarily the whole house has to be painted blue unless you just want to raise a feud.

Below is the example of that in React.

```
import { useState } from "react";

const Child = () => {
    const [count, setCount] = useState(0);

    return <div onClick={() => setCount(prev => prev + 1)}>COUNT {count}</div>
}
export default Child;
```
The Child component is then imported into App below.

```
import Child from './Child';
import Title from './Title';

const App = () => {
  return (
    <div>
        <Title/>
        <Child />
    </div>
  );
}

export default App;
```
By separating Child component from App, it is only normal if the state change in Child will only re-render Child right? After all only Child knows the existence of `count` state. And yes it is.

![Component Change in Elements Tab in DevTools. Only the count component that 'blinks' before changing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ms1bcm6f2pbkuvrqsfla.gif)

Or if we try to `console.log` in Child component,

```
import { useState } from "react";

const Child = () => {
    const [count, setCount] = useState(0);
    console.log('Rendering child')
    return <div onClick={() => setCount(prev => prev + 1)}>COUNT {count}</div>
}
export default Child;
```
it will look like this.

![How the components are rendered. Console log will only be called per clicking 'count'](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x58glrs5z2vdj2bhhrp7.gif)

## Virtual DOM
Then that silly late realization came to me: _Wait. React is still JavaScript after all right? Then it means there's actually a DOM manipulation for every props / state change right?_ Or in my understanding, these are the logics to do it in DOM manipulation:

1. Our algorithm has to **specifically know which** component that need to be changed. And to solve the _which_, usually we have to rely on selectors like ID, classname, etc.
2. After knowing the _which_ part, We have to query the specific component earlier. If such query is not possible (e.g: no selector is available), we might need replace the entire page with the new version, which will **re-render the whole body**.

Theoritically in programming, query is expensive. And I haven't even mentioned that this DOM change is performed by _listening_ to the variable used as the props / state, perhaps using bind or listener (I haven't researched deeper for this one though). So, always having to listen to changes, find the specific attribute, querying and altering the DOM per change... That's expensive.

But after all framework is meant to improve performance right? And _virtual DOM_ is what React came up with.

_Virtual_... Sounds so futuristic right? Lol.

![Like Sword Art Online floating castle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ejonue1ila0m47wvpob.png)

You can read more about this virtual DOM in the article I attached below, but just to summarize: it's a mechanism in which React will only re-render (or performing something similar to that crazy expensive computation earlier) after comparing the snapshots of the current and previous situation. Only after **there's actually a change**, the re-render happens.

Which also means, React won't re-render the component if the state is not changed.

```
import { useState } from "react";

const Child = () => {
    const [count, setCount] = useState(0);

    console.log('Render child')

    return <div onClick={() => setCount(0)}>Count {count}</div>
}
export default Child;
```

![Re-render doesn't happen anymore to Child component even after clicking 'count'](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vr3oig1lu0dxhw01j5tk.gif)

Really cool huh?
![Like witchcraft lol 🔮](https://i.giphy.com/media/zIwIWQx12YNEI/giphy.webp)

Okay this is the end of my writing today. Gotta save for the next article anyway right? 😌 Think I'll still write about `useState` again for the next few articles, perhaps something related about the state change between Component and its Child earlier? 👀 Stay tune!

## Further Readings
- [What is the virtual DOM in React?](https://blog.logrocket.com/virtual-dom-react/)