( callback: (...args: Args) => void | Promise<void>, debounceTimeoutMs: number | ((...args: Args) => number), )
| 33 | * debounce a text input). |
| 34 | */ |
| 35 | export function useDebouncedFunction< |
| 36 | // Parameterizing on the args instead of the whole callback function type to |
| 37 | // avoid type contravariance issues |
| 38 | Args extends unknown[] = unknown[], |
| 39 | >( |
| 40 | callback: (...args: Args) => void | Promise<void>, |
| 41 | debounceTimeoutMs: number | ((...args: Args) => number), |
| 42 | ): UseDebouncedFunctionReturn<Args> { |
| 43 | const timeoutIdRef = useRef<ReturnType<typeof setTimeout> | undefined>( |
| 44 | undefined, |
| 45 | ); |
| 46 | const cancelDebounce = useCallback(() => { |
| 47 | if (timeoutIdRef.current !== undefined) { |
| 48 | clearTimeout(timeoutIdRef.current); |
| 49 | } |
| 50 | |
| 51 | timeoutIdRef.current = undefined; |
| 52 | }, []); |
| 53 | |
| 54 | const debounceTimeRef = useRef(debounceTimeoutMs); |
| 55 | useEffect(() => { |
| 56 | debounceTimeRef.current = debounceTimeoutMs; |
| 57 | }, [debounceTimeoutMs]); |
| 58 | |
| 59 | const callbackRef = useRef(callback); |
| 60 | useEffect(() => { |
| 61 | callbackRef.current = callback; |
| 62 | }, [callback]); |
| 63 | |
| 64 | // Returned-out function will always be synchronous, even if the callback arg |
| 65 | // is async. Seemed dicey to try awaiting a genericized operation that can and |
| 66 | // will likely be canceled repeatedly |
| 67 | const debounced = useCallback( |
| 68 | (...args: Args): void => { |
| 69 | cancelDebounce(); |
| 70 | |
| 71 | timeoutIdRef.current = setTimeout( |
| 72 | () => void callbackRef.current(...args), |
| 73 | typeof debounceTimeRef.current === "function" |
| 74 | ? debounceTimeRef.current(...args) |
| 75 | : debounceTimeRef.current, |
| 76 | ); |
| 77 | }, |
| 78 | [cancelDebounce], |
| 79 | ); |
| 80 | |
| 81 | return { debounced, cancelDebounce } as const; |
| 82 | } |
| 83 | |
| 84 | /** |
| 85 | * Takes any value, and returns out a debounced version of it. |
no outgoing calls