Created
May 16, 2023 01:41
-
-
Save korrio/eb5dd101ea9249982de68708e5a65077 to your computer and use it in GitHub Desktop.
useInterval.ts
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 { useEffect, useRef } from 'react' | |
export const useInterval = ( | |
callback: () => Promise<void>, | |
delay: number | null | false | |
) => { | |
const savedCallback = useRef<() => Promise<void>>() | |
useEffect(() => { | |
savedCallback.current = callback | |
}, [callback]) | |
useEffect(() => { | |
const tick = () => { | |
savedCallback?.current() | |
} | |
if (delay) { | |
const id = setInterval(tick, delay) | |
return () => { | |
clearInterval(id) | |
} | |
} | |
}, [callback, delay]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment