Skip to content

Instantly share code, notes, and snippets.

@mattrossman
Created April 12, 2024 21:09
Show Gist options
  • Save mattrossman/dca40f59006d2331fe032c4095a6a792 to your computer and use it in GitHub Desktop.
Save mattrossman/dca40f59006d2331fe032c4095a6a792 to your computer and use it in GitHub Desktop.
useInterval
import { useEffect, useRef } from "react"
type UseIntervalOptions = {
callback: () => void
/** milliseconds */
delay: number
enabled?: boolean
firstRun?: boolean
}
export function useInterval({
callback,
delay,
enabled,
firstRun,
}: UseIntervalOptions) {
const callbackRef = useRef<() => void>(callback)
useEffect(() => {
callbackRef.current = callback
}, [callback])
useEffect(() => {
if (!enabled) return
if (firstRun) callbackRef.current()
const interval = window.setInterval(() => {
callbackRef.current()
}, delay)
return () => window.clearInterval(interval)
}, [delay, enabled, firstRun])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment