I was doing some tests with the following dummy component, where upon the execution (in the console) I am getting the following result:
Rendering: 0
Triggered: 0
Rendering: 4
Triggered: 4
Rendering: 4
I struggle to understand why.
First rendering:
- sets
indexto0. - runs useEffect as
undefinedis not0 - useEffect requests setting
indexto4
Second render:
indexis4- why useEffect body is executed again?
Third render:
- why there is re-rendering?
What I would expect is:
Rendering: 0
Triggered: 0
Rendering: 4
Am I skipping something very obvious? Could you please help me understand how this works under the hood?
const Example = React.memo(() => {
const [index, setIndex] = React.useState(0)
console.log('Rendering: ', index)
React.useEffect(() => {
console.log('Triggered: ', index)
setIndex(4)
}, [index])
return <h1>{index}</h1>
})
ReactDOM.render(<Example />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>