2

Why does the count increase by two each time using setinterval in react,The React version is 18

 const [count, setCount] = useState(0)
  useEffect(() => {
    setInterval(() => {
      setCount(count => count + 1)
    }, 1000)
  }, [])

  return (
    <div>{count}</div>
  )
simba
  • 21
  • 1
  • Does this answer your question? [React, can't access updated value of state variable inside function passed to setInterval() in useEffect()](https://stackoverflow.com/questions/72252967/react-cant-access-updated-value-of-state-variable-inside-function-passed-to-se) – Phil Aug 01 '23 at 00:01
  • Does this answer your question? [React Hooks: useEffect() is called twice even if an empty array is used as an argument](https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar) – Engr.Aftab Ufaq Aug 01 '23 at 06:17

1 Answers1

2

You want to clean up the interval.

You might be seeing it triggered twice because react mounts your component twice in debug mode to show you these kind of errors.

 const [count, setCount] = useState(0)
  useEffect(() => {
    const interval = setInterval(() => {
      setCount(count => count + 1)
    }, 1000)
    return () => clearInterval(interval)

  }, [])

  return (
    <div>{count}</div>
  )
Michael Brenndoerfer
  • 3,483
  • 2
  • 39
  • 50