-1

This question also relates to using updated Redux state inside functions in React components. I will like to know how can I use/update state inside some form of loop in React. Example:

useEffect(() => {
    const interval = setInterval(() => {
        setCount(count + 1)
        console.log('Count:', count)
    }, 3000);
    return () => clearInterval(interval)
}, [])

This returns to console:

Count: 0
Count: 0
Count: 0
Count: 0
...

What do I need to do to avoid this? (I would like to get Count: 0, Count: 1, Count: 2 as results)

nevo_e
  • 89
  • 8
  • 5
    Show the whole component. Using `count` within the effect is using stale data. You should also do `setCount(curr => curr + 1)` so that you don't accidentally use stale data when updating. – zero298 Sep 20 '21 at 18:13
  • Okay but how would you implement this in this problem where you wait for state to be updated? https://stackoverflow.com/questions/69242831/infinite-loop-based-on-state-in-react @Emile Bergeron – nevo_e Sep 20 '21 at 18:37

1 Answers1

3

you should pass a function to setCount :

useEffect(() => {
  const interval = setInterval(() => {
    setCount(prevCount => {
      console.log('Count:', prevCount)
      return prevCount + 1;
    });
  }, 3000);
  return () => clearInterval(interval)
}, [])
Olivier Boissé
  • 13,005
  • 5
  • 32
  • 49
  • Can you please help me with this problem because I do not know how to fix it even with this solution. https://stackoverflow.com/questions/69242831/infinite-loop-based-on-state-in-react – nevo_e Sep 20 '21 at 18:24