Search code examples
javascriptreactjstimerreact-hooks

how to clearInterval in react hook on clicking button


I am building a simple timer with react hooks. I have two buttons start and reset. handleStart function works fine when I click start button, the timer starts, but I can't figure out how to reset the timer on clicking the reset button. Here is my code

const App = () => {
  const [timer, setTimer] = useState(0)

  const handleStart = () => {
   let increment = setInterval(() => {
   setTimer((timer) => timer + 1)
  }, 1000)
}

const handleReset = () => {
  clearInterval(increment) // increment is undefined
  setTimer(0)
}

return (
  <div className="App">
    <p>Timer: {timer}</p>
    <button onClick={handleStart}>Start</button>
    <button onClick={handleReset}>Reset</button>
  </div>
);
}

In order to stop or reset the timer, I need to pass a property in clearInterval method. increment is defined in handleStart function so I can't access it in handleReset function. What to do?


Solution

  • You can set the timerId in ref and use it in your handleReset function. At present, the increment value is undefined for you because you have declared it within the handleStart function and hence hte scopre of the variable if limited to this function.

    Also you can't define it directly inside App component as a variable since it will get reset when the App component re-renders. This is where ref comes in handy.

    Below is a sample implementation

    const App = () => {
      const [timer, setTimer] = useState(0)
      const increment = useRef(null);
      const handleStart = () => {
       increment.current = setInterval(() => {
       setTimer((timer) => timer + 1)
      }, 1000)
    }
    
    const handleReset = () => {
      clearInterval(increment.current);
      setTimer(0);
    }
    
    return (
      <div className="App">
        <p>Timer: {timer}</p>
        <button onClick={handleStart}>Start</button>
        <button onClick={handleReset}>Reset</button>
      </div>
    );
    }