Last active
December 16, 2022 18:39
-
-
Save Ricaidito/93c448c616289d66bee54eb2d4e3dd0d to your computer and use it in GitHub Desktop.
Custom React hook with stopwatch behavior
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 { useState, useEffect } from "react"; | |
export const useStopwatch = () => { | |
const [time, setTime] = useState(0); | |
const [isRunning, setIsRunning] = useState(false); | |
useEffect(() => { | |
let interval; | |
if (isRunning) { | |
interval = setInterval(() => { | |
setTime(time => time + 1); | |
}, 1000); | |
} | |
return () => clearInterval(interval); | |
}, [isRunning]); | |
const toggleStopwatch = () => { | |
setIsRunning(isRunning => !isRunning); | |
}; | |
const resetStopwatch = () => { | |
setTime(0); | |
setIsRunning(false); | |
}; | |
return { time, isRunning, toggleStopwatch, resetStopwatch }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment