Created
April 12, 2024 21:09
-
-
Save mattrossman/dca40f59006d2331fe032c4095a6a792 to your computer and use it in GitHub Desktop.
useInterval
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 { 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