Skip to content

Instantly share code, notes, and snippets.

@aegiz
Last active July 27, 2021 06:33
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 aegiz/d91671c10d4f0095c613061d25111375 to your computer and use it in GitHub Desktop.
Save aegiz/d91671c10d4f0095c613061d25111375 to your computer and use it in GitHub Desktop.
Typescript implementation of useTimeout
/* 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