Home >Web Front-end >JS Tutorial >Why Doesn't My React State Update Inside `setInterval`?
State Not Updating When Utilizing React State Hook Within setInterval
Within React's new Hooks feature, the Clock component is designed to display a time value that increments every second. Despite the timer's operation, the time value remains stagnant at one.
The Cause of the Issue
The root of this problem lies in the setInterval's closure. The callback function within this closure only has access to the initial value of the time variable. As the useEffect() function does not execute after the first render, the callback does not receive subsequent time values.
Time Value Access
Consequently, the time variable always carries the initial value of zero in the callback for setInterval.
Solution: Using the Callback Form of State Hooks
Similar to the traditional setState method, state hooks offer two options: the first accepts an updated state, while the callback form receives the current state. To resolve this issue, it's recommended to utilize the callback form and acquire the most recent state value before incrementing within the setState callback.
Alternative Approaches
Dan Abramov's blog post delves into the use of setInterval with hooks, presenting different solutions for this problem. Reading it is highly recommended.
Updated Code
The below code demonstrates the corrected implementation:
function Clock() { const [time, setTime] = React.useState(0); React.useEffect(() => { const timer = window.setInterval(() => { setTime(prevTime => prevTime + 1); // <-- Change this line! }, 1000); return () => { window.clearInterval(timer); }; }, []); return (<div>Seconds: {time}</div>); } ReactDOM.render(<Clock />, document.querySelector('#app'));
The above is the detailed content of Why Doesn't My React State Update Inside `setInterval`?. For more information, please follow other related articles on the PHP Chinese website!