Created
July 16, 2020 06:02
-
-
Save smagch/953575e7fdbecd47a07de0e8f263200e to your computer and use it in GitHub Desktop.
useTimeout React 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
const useTimeout = (delay) => { | |
const [ timeoutFunc, setFunction ] = useState(null); | |
useEffect( | |
() => { | |
if (!timeoutFunc) { | |
return; | |
} | |
let mounted = true; | |
const timeoutId = setTimeout(() => { | |
if (mounted) { | |
timeoutFunc(); | |
} | |
}, delay); | |
return () => { | |
mounted = false; | |
clearTimeout(timeoutId); | |
}; | |
}, | |
[ delay, timeoutFunc ] | |
); | |
return { | |
started: !!timeoutFunc, | |
setFunction, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment