DEV Community

Omer Cohen
Omer Cohen

Posted on

Question About useEffect && setTimout

Hey,
each time i am resetting the counter to 3 ( on the second useEffect )
somehow the last useEffect is still running, so i get infinity timeouts calls.
*Clearing the timeout on the first useEffect fixes the proble, was wondering why its cauesing Infinity calls tho
Thanks for the help, srry for the bad english :)

const [counter, setCounter]  = useState(15)
 useEffect(() => {
  const timer = setTimeout(() => setCounter(counter - 1, 1000)
}, [counter])
useEffect(() => {
 if (counter === 0) {
  setCounter(3)
 }
}, [counter])

Top comments (3)

Collapse
 
savagepixie profile image
SavagePixie

You've got both useEffects to be dependant on counter. So whenever the value of counter changes, both useEffects are triggered.

You get an infinite loop because the second useEffect changes the value of counter, thus triggering both useEffects again.

Collapse
 
omercohenaviv profile image
Omer Cohen

Thanks for replaying :)

Mabye i was a bit missleading with the question,
I was expecting that when i setCounter(3) to just update the counter to 3, it does that but also somehow the last counter doesnt stop, which leads to ->
[(2,1,0)] -> [(2,1,0),(-1,-2,-3)] -> [(2,1,0),(-1,-2,-3), (-4,-5,-6)] ....

Collapse
 
savagepixie profile image
SavagePixie • Edited

I think what's going on is that the second useEffect triggers a new timeout while there is already one in place. When counter reaches 0 for the first time, you have two timeouts running instead of one. And every time the second useEffect fires, it changes counter, thus triggering another timeout. So the program keeps spawning timeouts that mess with the value of counter and consume memory.