Created
November 26, 2019 10:22
-
-
Save madflanderz/dd2e380df84e868d47f400b3dde319e7 to your computer and use it in GitHub Desktop.
useInterval hook
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" | |
function useInterval(callback: () => void, delay: number) { | |
const savedCallback = useRef<() => void | undefined>() | |
useEffect(() => { | |
savedCallback.current = callback | |
}) | |
useEffect(() => { | |
function tick() { | |
savedCallback.current && 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