Sometimes, we want to update states when we use React state hook within setInterval.
In this article, we’ll look at how to update states when we use React state hook within setInterval.
Update States When Using React State Hook within setInterval
We can set the state within the setInterval
callback to update the state when it’s run.
For instance, we can write:
const App = () => {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
const timer = window.setInterval(() => {
setCount(count => count + 1)
}, 1000);
return () => {
window.clearInterval(timer);
};
}, []);
return (
<div>{count}</div>
);
}
We add the setInterval
function into the useEffect
callback.
We call setCount
inside the callback by passing in a callback that returns the count + 1
.
count
is the state that we want to set.
We return a function to clear the timer with clearInterval
so that it’s cleared when the component unmounts.
The empty array will ensure that the useEffect
callback is run when the component mounts.
Conclusion
We can set the state within the setInterval
callback to update the state when it’s run.