3

I am trying to update (increment) a React state (counter) every setInterval function but it is don't work as expected. For the first 5 or so seconds, the count is rendered with consistent increments but after that it increases randomly and doesn't stop.

export default function App() {

  const [count, setCount] = useState(0);
  setInterval(() => setCount((oldCount) => oldCount + 1), 1000);

  return (<>
    <div>{count}</div>
  </>);
};

How can I achieve this and the same for time intervals less than a second ( 100 or 10ms ) ?

Saarthak
  • 39
  • 1
  • 2
  • 5
  • "it doesn't work as expected", what do you expect? Where is the full code? Please read [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Dennis Vash Aug 06 '21 at 18:07

1 Answers1

5

You need to run the interval in useEffect there are plenty of such examples:

export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setCount((oldCount) => oldCount + 1), 1000);

    return () => {
      clearInterval(id);
    };
  }, []);

  return (
    <>
      <div>{count}</div>
    </>
  );
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • Can you explain why useEffect is required here ? – Saarthak Aug 06 '21 at 18:55
  • useEffect with empty dep array allows running a callback once on component's mount, it mentioned in the docs: https://reactjs.org/docs/hooks-reference.html#useeffect, and you can read further here: https://stackoverflow.com/questions/59841800/react-useeffect-in-depth-use-of-useeffect/59841947#59841947 – Dennis Vash Aug 06 '21 at 21:52