To read the whole doc in detail: React cleaner use of setTimeout
Last active
February 8, 2023 12:10
-
-
Save sarthakxv/3054dd1eae727f4aaf37bbf56d1bdaaf to your computer and use it in GitHub Desktop.
React cleaner use of setTimeout
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
| 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; |
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
| 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