Home > Enterprise >  how to use updated state in react [duplicate]
how to use updated state in react [duplicate]

Time:09-21

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)

CodePudding user response:

you should pass a function to setCount :

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