Search code examples
javascriptreactjssetintervaluse-effect

what happend re-define setInterval to variable in useEffect hook?


I want to know what happened if I define setInterval function repeatedly to same variable in react hook useEffect.

I checked variable have new setInterval id value every defining. But I wonder is there instance remained in memory about previous setInterval timer, even if new setInterval defined at same variable??

 useEffect(() => {
    const timer = setInterval(
      () => {
        if (count < elementLength - 1) {
          boolean.current = false;
          setCount(prev => prev + 1);
        } else {
          boolean.current = true;
          setCount(0);
        }
      },
      boolean.current ? 50 : 2500
    );

    return () => {
      clearInterval(timer);
    };
  }, [count]);

Solution

  • What happens if I assign repeatedly to same variable?

    It's not the same variable. It's creating a fresh new timer variable every time the effect runs. They're all independent.

    But I wonder is there instance remained in memory about previous timer

    Yes and no. The cleanup function returned by the useEffect callback is a closure over the timer, and it is kept in memory by React as long as necessary. In practice, it will be called once when the component unmounts or its dependencies change, and can be garbage-collected afterwards, taking with it the respective timer variable.