Skip to content

Instantly share code, notes, and snippets.

@hyber1z0r
Last active August 10, 2020 19:39
Show Gist options
  • Save hyber1z0r/19d7fef4086c52bab4de496d6681b356 to your computer and use it in GitHub Desktop.
Save hyber1z0r/19d7fef4086c52bab4de496d6681b356 to your computer and use it in GitHub Desktop.
useTimeout hook
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;
@kevin-guertin
Copy link

Line 7 and 12 generates a typescript error:
Type '() => void' is not assignable to type 'undefined'.

image

@hyber1z0r
Copy link
Author

Line 7 and 12 generates a typescript error:
Type '() => void' is not assignable to type 'undefined'.

image

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment