I'm trying to understand how React works under the hood and there is something that I cannot found anywhere and that I can't figure out by myself.
I know that whenever we change the state of a component using setX
, React compares the new representation of the Virtual DOM with the one it already has and, if there is anything to change in the real DOM, then it goes ahead and flushes those changes.
To see this in action I created a component like this one:
<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.6/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">
const {useEffect, useState} = React;
const App = () => {
const [counter, setCounter] = useState(1);
console.log('in component');
useEffect(() => {
console.log('in useEffect');
});
return (
<>
<div>{counter}</div>
<button onClick={() => setCounter(2)}>
Increment
</button>
</>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
</script>
Initially, when the component mounts, it is logged:
in component
in useEffect
The same when I click the button once. And if I click one more time, it just logs:
in component
I guess this time we don't see the in useEffect
because React correctly came to the conclusion that there is nothing to change in the DOM.
Ok. It makes completely sense.
The thing is the next time I click, I'd expect to see again the in component
, but nothing happens. And the same applies to the following clicks.
Why does this happen?