Skip to content

Instantly share code, notes, and snippets.

@nilsandrey
Last active May 2, 2024 02:52
Show Gist options
  • Save nilsandrey/2504ea7eb72a336499e0d7fce6c2124d to your computer and use it in GitHub Desktop.
Save nilsandrey/2504ea7eb72a336499e0d7fce6c2124d to your computer and use it in GitHub Desktop.
React useTimeout hook (by Chris Bongers)
// 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