Skip to content

Instantly share code, notes, and snippets.

@yashshah1
Last active November 23, 2021 11:10
Show Gist options
  • Save yashshah1/ca32d350b26f38fc2851c874a14bec72 to your computer and use it in GitHub Desktop.
Save yashshah1/ca32d350b26f38fc2851c874a14bec72 to your computer and use it in GitHub Desktop.
useTimeout hook
import { useEffect, useRef } from "react";
const useTimeout = (callback, delay) => {
const timeoutRef = useRef(null);
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
if (typeof delay === "number") {
timeoutRef.current = setTimeout(callbackRef.current, delay);
return () => clearTimeout(timeoutRef.current);
}
}, [delay]);
};
export default useTimeout;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment