DEV Community

Jessica Cecilia Budianto
Jessica Cecilia Budianto

Posted on • Originally published at linkedin.com

React: how I understand Virtual DOM through useState

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

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

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 only 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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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

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;
Enter fullscreen mode Exit fullscreen mode

it will look like this.

How the components are rendered. Console log will only be called per clicking 'count'

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

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;
Enter fullscreen mode Exit fullscreen mode

Re-render doesn't happen anymore to Child component even after clicking 'count'

Really cool huh?
Like witchcraft lol 🔮

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

Top comments (2)

Collapse
 
voko profile image
Ko

Functional components, unlike HTML_DOM, cannot be interacted with. React is no longer VirtualDOM

Collapse
 
jessicacb12 profile image
Jessica Cecilia Budianto

Woah really? Now I just know this. Time to learn more then, thanks!