Last active
November 23, 2021 11:10
-
-
Save yashshah1/ca32d350b26f38fc2851c874a14bec72 to your computer and use it in GitHub Desktop.
useTimeout hook
This file contains 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
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