Last active
August 10, 2020 19:39
-
-
Save hyber1z0r/19d7fef4086c52bab4de496d6681b356 to your computer and use it in GitHub Desktop.
useTimeout hook
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 React, { useEffect, useRef } from 'react'; | |
const useTimeout = (callback: () => void, delay: number | null) => { | |
const savedCallback = useRef(callback); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
useEffect(() => { | |
function tick() { | |
savedCallback.current(); | |
} | |
if (delay !== null) { | |
const id = setTimeout(tick, delay); | |
return () => clearTimeout(id); | |
} | |
}, [delay]); | |
}; | |
export default useTimeout; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for pointing that out. I updated the gist to include the callback into the
useRef
call so that Typescript understands it will never be undefined.