Created
June 13, 2023 14:59
-
-
Save thivi/88c6730f2bfe805e80b5bfd0d3d4ca64 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
const Timer = () => { | |
const [seconds, setSeconds] = useState(0); | |
const [isActive, setIsActive] = useState(false); | |
const handleTimerClick = () => { | |
setIsActive(!isActive); | |
}; | |
React.useEffect(() => { | |
let interval = null; | |
if (isActive) { | |
interval = setInterval(() => { | |
setSeconds((prevSeconds) => prevSeconds + 1); | |
}, 1000); | |
} else if (!isActive && seconds !== 0) { | |
clearInterval(interval); | |
} | |
return () => { | |
clearInterval(interval); | |
}; | |
}, [isActive, seconds]); | |
return ( | |
<div> | |
<h1>Timer: {seconds} seconds</h1> | |
<button onClick={handleTimerClick}> | |
{isActive ? 'Pause' : 'Start'} | |
</button> | |
</div> | |
); | |
}; | |
export default Timer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment