Created
November 1, 2019 14:32
-
-
Save ahtcx/884e41b5212a4da009edcc1aab9913a0 to your computer and use it in GitHub Desktop.
TypeScript version of Dan Abramov's `useInterval`
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' | |
type Callback = () => void | |
export const useInterval = (callback: Callback, delay: number | null = null) => { | |
const savedCallback = useRef<Callback>() | |
useEffect(() => { | |
savedCallback.current = callback | |
}, [callback]) | |
useEffect(() => { | |
const tick = () => savedCallback.current?.() | |
if (delay !== null) { | |
const id = window.setInterval(tick, delay) | |
return () => window.clearInterval(id) | |
} | |
}, [delay]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment