Created
February 14, 2024 18:51
-
-
Save cristoferespindola/d469891e580049fe34a5ac214f1503ec to your computer and use it in GitHub Desktop.
useDebouncedFunction
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 { useRef } from 'react' | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
type Func = (...args: any[]) => any | |
type DebouncedFunction<F extends Func> = (...args: Parameters<F>) => Promise<undefined | ReturnType<F>> | |
export function useDebouncedFunction<F extends Func>( | |
func: F | undefined, | |
milliseconds: number | |
): DebouncedFunction<F> | undefined { | |
const timeoutIdRef = useRef<number | undefined>() | |
if (!func) { | |
return undefined | |
} | |
const debounced: DebouncedFunction<F> = (...args: Parameters<F>) => { | |
return new Promise((resolve) => { | |
if (timeoutIdRef.current !== undefined) { | |
clearTimeout(timeoutIdRef.current) | |
} | |
timeoutIdRef.current = window.setTimeout(() => { | |
resolve(func(...args)) | |
timeoutIdRef.current = undefined | |
}, milliseconds) | |
}) | |
} | |
return debounced | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment