Until today I thought that code inside an useEffect without dependency array and code outside useEffect both trigger on every rerender, but then I found this weird case and I don't understand why is this happening.
In THIS example, the first time you click the button it triggers a setState to a different value so it rerenders and both console.log are called, but the second time you click the button a setState is called with the same value, still the outside console.log gets called, but the console.log inside useEffect doesn't... why? Is this not a full rerender? How can the component get reevaluated without triggering useEffect again?
The next time you click the button nothing happens because calling setState with the same value doesnt trigger a rerender, but the first time does that weird half-rerender thing that I dont understand.
Thanks in advance.
I will answer my question:
This behavior is actually explained in the official docs and nothing to worry about since it's not a "real" render.
This is the relevant part:
If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. [...]
So basically React evaluates the function, so the outside console.log will be called but then it just bails out without rerendering the children or firing useEffect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With