Created
March 5, 2020 23:17
-
-
Save grantglidewell/5ee08b79dea05894a817b8a83b920386 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' | |
function useTimeout(callback, delay) { | |
const savedCallback = useRef() | |
// Remember the latest callback. | |
useEffect( | |
() => { | |
savedCallback.current = callback | |
}, | |
[callback] | |
) | |
// Set up the interval. | |
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