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)
You've got both
useEffect
s to be dependant oncounter
. So whenever the value ofcounter
changes, bothuseEffect
s are triggered.You get an infinite loop because the second
useEffect
changes the value ofcounter
, thus triggering bothuseEffect
s again.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)] ....
I think what's going on is that the second
useEffect
triggers a new timeout while there is already one in place. Whencounter
reaches 0 for the first time, you have two timeouts running instead of one. And every time the seconduseEffect
fires, it changescounter
, thus triggering another timeout. So the program keeps spawning timeouts that mess with the value of counter and consume memory.