I’m writing an incremental-style game in React and I have this setInterval inside App.ts:
useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(time + 1); } }, rate); return () => clearInterval(loop); });
I’ve also got various event handlers along the lines of:
<button onClick={() => increment(counter + 1)}>Increment</button>
Unfortunately, if I click that button multiple times in a second, it will block the setInterval from updating the time
state.
This state using the hooks as well as Redux stored state.
How can I, at the very least, make my setInterval tick reliably, so that I can click around the page without blocking it?
Advertisement
Answer
Do it like that
[]
empty dependency means only execute when a component will mount.
useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(prev => prev + 1); } }, rate); return () => clearInterval(loop); }, []); <--- add that []
Notes
- adding time as a dependency will create an infinite loop
- you need to add
runStatus
orrate
variable as a dependency if its dynamic state