Skip to content

Instantly share code, notes, and snippets.

@thivi
Created June 13, 2023 15:09
Show Gist options
  • Save thivi/b3ca6bc29a2544e2e040576441c192c0 to your computer and use it in GitHub Desktop.
Save thivi/b3ca6bc29a2544e2e040576441c192c0 to your computer and use it in GitHub Desktop.
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);
}
return () => {
clearInterval(interval);
};
}, [isActive]);
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