Home > Web Front-end > JS Tutorial > Why Doesn't My React State Update Inside `setInterval`?

Why Doesn't My React State Update Inside `setInterval`?

Mary-Kate Olsen
Release: 2024-12-02 19:43:11
Original
1002 people have browsed it

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'));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template