Created
July 17, 2022 03:20
-
-
Save itsMapleLeaf/801ce0e9784b247324281cf92d081753 to your computer and use it in GitHub Desktop.
React useTimer hook
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 { useRef, useState } from "react" | |
import { useEvent } from "./use-event" | |
export function useTimer(duration: number) { | |
const [running, setRunning] = useState(false) | |
const timeoutRef = useRef<ReturnType<typeof setTimeout>>() | |
const start = useEvent(() => { | |
clearTimeout(timeoutRef.current) | |
setRunning(true) | |
timeoutRef.current = setTimeout(() => setRunning(false), duration) | |
}) | |
const stop = useEvent(() => { | |
clearTimeout(timeoutRef.current) | |
setRunning(false) | |
}) | |
return { running, start, stop } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment