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?