Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not able to clear Interval using variable which is outside the react hook

I am trying to access clearTimerInterval in clearTimer method but getting undefined , got the waring variable from inside React Hook will be lost after each render. in below code useEffect hook called once once then how variable clearTimerInterval got undefined?

function Child(props) {
          let [timerCount, setTimer] = useState(0);
          var clearTimerInterval;
          useEffect(() => {
            clearTimerInterval = setInterval(() => {
              setTimer(timerCount => {
                return timerCount + 1;

              });
            }, 1000);
            return () => {
              clearInterval(clearTimerInterval);
            };
          }, []);

          function clearTimer() {
            clearInterval(clearTimerInterval);
          }
          return (
            <div>
              <div>Timer {timer}</div>
              <button onClick={clearTimer}>ClearTimer</button>
            </div>
          );
        }

        export default React.memo(Child);
like image 356
ankit Avatar asked Sep 08 '25 00:09

ankit


1 Answers

If you need to save variables across re-renders use useRef which in this case acts like a class instance field, also note that mutations to refs does not trigger a re-render.

This will give you the ability to clear the interval from outside of useEffect

function Child(props) {
  let [timerCount, setTimer] = useState(0)
  const intervalRef = useRef(null)

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setTimer(prevState => prevState + 1)
    }, 1000)

    return () => clearInterval(intervalRef.current)
  }, [])

  function clearTimer() {
    clearInterval(intervalRef.current)
    intervalRef.current = null
  }

  return (
    <div>
      <div>Timer {timerCount}</div>
      <button onClick={clearTimer}>ClearTimer</button>
    </div>
  )
}
like image 61
Asaf Aviv Avatar answered Sep 10 '25 11:09

Asaf Aviv