Skip to content

Instantly share code, notes, and snippets.

@parwatcodes
Created February 18, 2025 01:48
Show Gist options
  • Save parwatcodes/75a0cf581652bb8af695c93a4c9f3c4b to your computer and use it in GitHub Desktop.
Save parwatcodes/75a0cf581652bb8af695c93a4c9f3c4b to your computer and use it in GitHub Desktop.
Performant timer js code for react comp
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