Created
February 18, 2025 01:48
-
-
Save parwatcodes/75a0cf581652bb8af695c93a4c9f3c4b to your computer and use it in GitHub Desktop.
Performant timer js code for react comp
This file contains hidden or 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 from 'react'; | |
const App = () => { | |
const [timer, setTimer] = React.useState(0); | |
const intervalRef = React.useRef<null | number>(null); | |
function timer_handler() { | |
setTimer(timer => timer + 1); | |
} | |
React.useEffect(() => { | |
const intervalId = setInterval(timer_handler, 1000); | |
intervalRef.current = intervalId; | |
return () => clearInterval(intervalId); | |
}, []); | |
const handleStopTimer = () => { | |
if (intervalRef.current) { | |
clearInterval(intervalRef.current); | |
intervalRef.current = null; | |
} else { | |
intervalRef.current = setInterval(timer_handler, 1000); | |
} | |
}; | |
return ( | |
<React.Fragment> | |
<div>{timer}</div> | |
<button onClick={handleStopTimer}>Stop timer</button> | |
</React.Fragment> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment