Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useEffect not re-rendering

  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!

like image 569
cheems Avatar asked Sep 21 '25 04:09

cheems


1 Answers

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.

like image 178
Nicholas Tower Avatar answered Sep 22 '25 20:09

Nicholas Tower