Skip to content

Instantly share code, notes, and snippets.

@smagch
Created July 16, 2020 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smagch/953575e7fdbecd47a07de0e8f263200e to your computer and use it in GitHub Desktop.
Save smagch/953575e7fdbecd47a07de0e8f263200e to your computer and use it in GitHub Desktop.
useTimeout React hook
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