Last active
May 2, 2024 02:52
-
-
Save nilsandrey/2504ea7eb72a336499e0d7fce6c2124d to your computer and use it in GitHub Desktop.
React useTimeout hook (by Chris Bongers)
This file contains hidden or 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
// From <https://dev.to/dailydevtips1/react-cleaner-use-of-settimeout-105m> | |
import { useCallback, useEffect, useRef, useMemo } from 'react'; | |
/** | |
* To use the hook | |
* ``` | |
* import useTimeout from './useTimeout'; | |
* | |
* const [timeout] = useTimeout(() => { | |
* setShow(false); | |
* }, 1500); | |
* | |
* timeout(); | |
* ``` | |
*/ | |
export default function useTimeout(callback, delay) { | |
const timeoutRef = useRef(); | |
const callbackRef = useRef(callback); | |
useEffect(() => { | |
callbackRef.current = callback; | |
}, [callback]); | |
useEffect(() => { | |
return () => window.clearTimeout(timeoutRef.current); | |
}, []); | |
const memoizedCallback = useCallback( | |
(args) => { | |
if (timeoutRef.current) { | |
window.clearTimeout(timeoutRef.current); | |
} | |
timeoutRef.current = window.setTimeout(() => { | |
timeoutRef.current = null; | |
callbackRef.current?.(args); | |
}, delay); | |
}, | |
[delay, timeoutRef, callbackRef] | |
); | |
return useMemo(() => [memoizedCallback], [memoizedCallback]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment