React, can't access updated value of state variable inside function passed to setInterval() in useEffect()
Asked Answered
M

1

6

I am building a simple clock app with React. Currently the countDown() function works, but I would like the user to be able to stop/start the clock by pressing a button. I have a state boolean called paused that is inverted when the user clicks a button. The trouble is that after the value of paused is inverted, the reference to paused inside the countDown() function passed to setInterval() seems to be accessing the default value of paused, instead of the updated value.

function Clock(){
  const [sec, setSecs] = useState(sessionLength * 60);
  const [paused, setPaused] = useState(false);
 
  const playPause = () => {
    setPaused(paused => !paused);
  };
  
  const countDown = () => {
    if(!paused){
        setSecs(sec => sec - 1)
      }
  }
  
  useEffect(() => {
    const interval = setInterval(() => {
        countDown();
    }, 1000);
    return () => {
      clearInterval(interval);
    };
  }, []);

I'm assuming it has something to do with the asynchronous nature of calls to setState() in React, and/or the nature of scoping/context when using regular expressions. However I haven't been able to determine what is going on by reading documentation related to these concepts.

I can think of some workarounds that would allow my app to function as desired. However I want to understand what is wrong with my current approach. I would appreciate any light anyone can shed on this!

Misvalue answered 15/5, 2022 at 23:48 Comment(8)
Try using useCallback?Wert
In your code, the useEffect is called only once when mounting the component. The countdown function registered inside will have its initial value at the time when the useEffect/setInterval is called. So paused will only have the value when you initially mount the component. Because you are not calling countDown directly or updating its value inside your useEffect, it is not updated.Sidewalk
@Phil setStartTime() is part of some workaround code that I meant to remove, I will fix that.Misvalue
@KevinAmiranoff what confuses me about this is that setInterval() is called every second, and is successfully updating the sec variable each time. What I don't understand is why the current value of the boolean paused isn't accessed.Misvalue
setInterval is called only one! You want only one timer at once to be running (in your use case at least). On the contrary the function you call inside, here countDown, is called every interval (1000ms in your exemple)Sidewalk
Because you define countDown in the component body, every time your component re-renders, that function is re-defined. The one captured in setInterval() is from the first render which also captures the first paused state value. Basically a very nuanced example of the complexity involved in React's render cycle. This is a really good question to have on StackOverflowGrandfather
Here's a contrived but hopefully understandable simplified example ~ jsfiddle.net/vbcw08qpGrandfather
Thank you, that does clarify what is happening and the example is helpful!Misvalue
S
4

In your code, the useEffect is called only once when mounting the component.

The countdown function registered inside will have its initial value at the time when the useEffect/setInterval is called. So paused will only have the value when you initially mount the component. Because you are not calling countDown directly or updating its value inside your useEffect, it is not updated.

I think you could solve this issue like this:

  interval.current = useRef(null);
  const countDown = () => {
    if(!paused){
        setSecs(sec => sec - 1)
      }
  }
  
  useEffect(() => {
    clearInterval(interval.current);
    interval.current = setInterval(countDown, 1000);
    return () => {
      clearInterval(interval.current);
    };
  }, [paused]);

your useEffect is dependent on the value of paused as it needs to create a new interval (with a different countdown function). This will trigger the useEffect not only on mount but every time paused changes. So one solution would be to clear the interval and start a new one with a different callback function.

Edit: You could actually improve it as you only want the interval to be running if the countDown function actually does something so this should work too:

 useEffect(() => {
    clearInterval(interval.current);
    if(!paused) {
      interval.current = setInterval(countDown, 1000);
    }
    return () => {
      clearInterval(interval.current);
    };
  }, [paused]);
Sidewalk answered 16/5, 2022 at 0:17 Comment(4)
Thanks, that worked! Forgive me but I'm still slightly unclear on why it's necessary. I understand that without this code, the value of paused is only evaluated when useEffect() is called, and I understand how this code fixes the problem by calling useEffect and passing an updated function each time paused changes. I'm still a bit confused about why the value of paused is only evaluated when useEffect is called, and not every time countDown executes.Misvalue
So, React re-renders a component every time a prop or state changes. But the useEffect with empty array for dependency triggers the function declared as first argument only on the first render. At that time paused is false. And even if the function countDown is recreated every render, the function inside useEffect is not. So the value of countDown inside that useEffect is actually the one that was read at the time of the initial render. Hopefully this make sense?Sidewalk
It can be confusing because it might look like setInterval is called every second with a new countDown function but it is not. It is only called once and will trigger the function passed as first argument for every interval but with the value defined at the moment when setInterval is called.Sidewalk
Yes, thank you I think I understand now. This, combined with the comments above (on the question) cleared it up for me. I think part of my confusion was that I wasn't aware that what allows the state variables to stay updated is the re-rendering of the component - I was imagining that any time the value changed, any references to it would be notified.Misvalue

© 2022 - 2024 — McMap. All rights reserved.