Last active
July 27, 2021 06:33
-
-
Save aegiz/d91671c10d4f0095c613061d25111375 to your computer and use it in GitHub Desktop.
Typescript implementation of useTimeout
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
/* eslint-disable import/prefer-default-export */ | |
/** | |
* Create a setTimeout on demand | |
* See: https://www.joshwcomeau.com/snippets/react-hooks/use-timeout/ | |
*/ | |
import { MutableRefObject, useEffect, useRef } from 'react'; | |
export const useTimeout = (callback: () => void, delay: number): MutableRefObject<number> => { | |
const timeoutRef = useRef<number>(0); // not sure about this one 🙃 | |
const savedCallback = useRef<() => void>(callback); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}); | |
useEffect(() => { | |
const tick = () => savedCallback.current(); | |
if (typeof delay === 'number') { | |
timeoutRef.current = window.setTimeout(tick, delay); | |
return () => window.clearTimeout(timeoutRef.current); | |
} | |
}, [delay]); | |
return timeoutRef; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment