Skip to content

Instantly share code, notes, and snippets.

@sarthakxv
Last active February 8, 2023 12:10
Show Gist options
  • Select an option

  • Save sarthakxv/3054dd1eae727f4aaf37bbf56d1bdaaf to your computer and use it in GitHub Desktop.

Select an option

Save sarthakxv/3054dd1eae727f4aaf37bbf56d1bdaaf to your computer and use it in GitHub Desktop.
React cleaner use of setTimeout
import useTimeout from './useTimeout';
const Index = () => {
const [show, setShow] = useState<boolean>(false);
const [timeout] = useTimeout(() => {
setShow(true);
}, 2000);
return (
<div>{!show ? <p>Loading...</p> : <p>I am fully loaded</p>}</div>
);
};
export default Index;
import { useEffect, useCallback, useMemo, useRef } from "react";
/**
*
* @param callback - An action that should happen after the timeout
* @param delay - Time for it to timeout
* @returns A function that can be invoked to start it
*/
export default function useTimeout(callback: any, delay: number) {
const timeoutRef = useRef();
const callbackRef = useRef(callback);
// Listent to the callback incase it changes
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
// Cleanup effect for the timeout
useEffect(() => {
return () => window.clearTimeout(timeoutRef.current);
}, []);
const memoizedCallback = useCallback(
(args: any) => {
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