Reputation: 59
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 ) ?
Upvotes: 4
Views: 12134
Reputation: 53874
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>
</>
);
}
Upvotes: 8