const [count, setCount]=useState(0);
useEffect(()=>{
console.log("count inside hook is ", count);
},[count]);
if(count<10)
setCount(count+1); // setCount(count=>count+1)
I have this code, I expected to the console for every count, but I can only see console log for count=10.
My understanding is that given a dependency array, useEffect must be called when the object inside it changes, but this doesn't happens here. Can someone please explain why is this happening?
Thanks!
If you set state during rendering, then it essentially aborts the current render. After you return, react doesn't push the interim changes to the dom, and doesn't run effects. Instead, it starts the new render with the new state. Eventually, once you hit 10, you stop setting state mid-render, and that final render can complete and run its 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