Created
September 20, 2021 18:41
-
-
Save harrisrobin/61bb61cc10a9bf3b82f71f24bde571c8 to your computer and use it in GitHub Desktop.
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" | |
import { noop } from "../../utils" | |
export function useInterval( | |
callback: () => void, | |
delay: number | null | false, | |
immediate?: boolean, | |
) { | |
const savedCallback = useRef(noop) | |
// Remember the latest callback. | |
useEffect(() => { | |
savedCallback.current = callback | |
}) | |
// Execute callback if immediate is set. | |
useEffect(() => { | |
if (!immediate) return | |
if (delay === null || delay === false) return | |
savedCallback.current() | |
}, [immediate, delay]) | |
// Set up the interval. | |
useEffect(() => { | |
if (delay === null || delay === false) return undefined | |
const tick = () => savedCallback.current() | |
const id = setInterval(tick, delay) | |
return () => clearInterval(id) | |
}, [delay]) | |
} | |
export default useInterval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment