Skip to content
Advertisement

How can I make state updating asynchronous in React+Redux

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

  1. adding time as a dependency will create an infinite loop
  2. you need to add runStatus or rate variable as a dependency if its dynamic state
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement