This is from another question that was asked by somebody, regarding state within a setInterval.
The question was why the state didn't update beyond 1. The answer was
The reason is because the callback passed into setInterval's closure only accesses the time variable in the first render, it doesn't have access to the new time value in the subsequent render because the useEffect() is not invoked the second time.
time always has the value of 0 within the setInterval callback.
Like the setState you are familiar with, state hooks have two forms: one where it takes in the updated state, and the callback form which the current state is passed in. You should use the second form and read the latest state value within the setState callback to ensure that you have the latest state value before incrementing it.
function Clock() {
const [time, setTime] = React.useState(0);
React.useEffect(() => {
const timer = window.setInterval(() => {
setTime(prevTime => prevTime + 1); <----this line was edited which makes the counter work according to the answer provided.
}, 1000);
return () => {
window.clearInterval(timer);
};
}, []);
return (
<div>Seconds: {time}</div>
);
}
ReactDOM.render(<Clock />, document.querySelector('#app'));
My question is, is it possible to use an if statement within that interval that uses the updated version of the time state? I tried console logging inside and outside of the interval and within the interval the counter doesn't update, while outside of it the state is updated. This makes sense given the previous answer but is there a way to use the updated version of the state inside the interval? Or perhaps a way around it?
For example maybe there is an if statement that uses the time state and a modulus operator with possibly another state, and plays a different sound according to the result of the calculation.