Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created July 17, 2022 03:20
Show Gist options
  • Save itsMapleLeaf/801ce0e9784b247324281cf92d081753 to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/801ce0e9784b247324281cf92d081753 to your computer and use it in GitHub Desktop.
React useTimer hook
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