sjsanc
sjsanc

Reputation: 45

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?

Upvotes: 0

Views: 58

Answers (1)

Nisharg Shah
Nisharg Shah

Reputation: 19532

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

Upvotes: 2

Related Questions