user9258981
user9258981

Reputation: 155

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?

Upvotes: 5

Views: 5183

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281686

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>
);
}

Upvotes: 14

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4598

Why not use hooks feature directly?

Define a interval state as you have defined timer state.

const [intervalval, setIntervalval] = useState()

Now you in handleStart set the state and in clearinterval you will have access to the modified state.

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


const handleReset = () => {
      clearInterval(intervalval);
      setTimer(0);
}

Upvotes: 4

Related Questions