|
| 1 | +/** |
| 2 | + * @file Defines hooks for created debounced versions of functions and arbitrary |
| 3 | + * values. |
| 4 | + * |
| 5 | + * It is not safe to call a general-purpose debounce utility inside a React |
| 6 | + * render. It will work on the initial render, but the memory reference for the |
| 7 | + * value will change on re-renders. Most debounce functions create a "stateful" |
| 8 | + * version of a function by leveraging closure; but by calling it repeatedly, |
| 9 | + * you create multiple "pockets" of state, rather than a centralized one. |
| 10 | + * |
| 11 | + * Debounce utilities can make sense if they can be called directly outside the |
| 12 | + * component or in a useEffect call, though. |
| 13 | + */ |
| 14 | +import { useCallback, useEffect, useRef, useState } from "react"; |
| 15 | + |
| 16 | +type useDebouncedFunctionReturn<Args extends unknown[]> = Readonly<{ |
| 17 | + debounced: (...args: Args) => void; |
| 18 | + |
| 19 | + // Mainly here to make interfacing with useEffect cleanup functions easier |
| 20 | + cancelDebounce: () => void; |
| 21 | +}>; |
| 22 | + |
| 23 | +/** |
| 24 | + * Creates a debounce function that is resilient to React re-renders, as well as |
| 25 | + * a function for canceling a pending debounce. |
| 26 | + * |
| 27 | + * The returned-out functions will maintain the same memory references, but the |
| 28 | + * debounce function will always "see" the most recent versions of the arguments |
| 29 | + * passed into the hook, and use them accordingly. |
| 30 | + * |
| 31 | + * If the debounce time changes while a callback has been queued to fire, the |
| 32 | + * callback will be canceled completely. You will need to restart the debounce |
| 33 | + * process by calling the returned-out function again. |
| 34 | + */ |
| 35 | +export function useDebouncedFunction< |
| 36 | + // Parameterizing on the args instead of the whole callback function type to |
| 37 | + // avoid type contra-variance issues |
| 38 | + Args extends unknown[] = unknown[], |
| 39 | +>( |
| 40 | + callback: (...args: Args) => void | Promise<void>, |
| 41 | + debounceTimeMs: number, |
| 42 | +): useDebouncedFunctionReturn<Args> { |
| 43 | + const timeoutIdRef = useRef<number | null>(null); |
| 44 | + const cancelDebounce = useCallback(() => { |
| 45 | + if (timeoutIdRef.current !== null) { |
| 46 | + window.clearTimeout(timeoutIdRef.current); |
| 47 | + } |
| 48 | + |
| 49 | + timeoutIdRef.current = null; |
| 50 | + }, []); |
| 51 | + |
| 52 | + const debounceTimeRef = useRef(debounceTimeMs); |
| 53 | + useEffect(() => { |
| 54 | + cancelDebounce(); |
| 55 | + debounceTimeRef.current = debounceTimeMs; |
| 56 | + }, [cancelDebounce, debounceTimeMs]); |
| 57 | + |
| 58 | + const callbackRef = useRef(callback); |
| 59 | + useEffect(() => { |
| 60 | + callbackRef.current = callback; |
| 61 | + }, [callback]); |
| 62 | + |
| 63 | + // Returned-out function will always be synchronous, even if the callback arg |
| 64 | + // is async. Seemed dicey to try awaiting a genericized operation that can and |
| 65 | + // will likely be canceled repeatedly |
| 66 | + const debounced = useCallback( |
| 67 | + (...args: Args): void => { |
| 68 | + cancelDebounce(); |
| 69 | + |
| 70 | + timeoutIdRef.current = window.setTimeout( |
| 71 | + () => void callbackRef.current(...args), |
| 72 | + debounceTimeRef.current, |
| 73 | + ); |
| 74 | + }, |
| 75 | + [cancelDebounce], |
| 76 | + ); |
| 77 | + |
| 78 | + return { debounced, cancelDebounce } as const; |
| 79 | +} |
| 80 | + |
| 81 | +/** |
| 82 | + * Takes any value, and returns out a debounced version of it. |
| 83 | + */ |
| 84 | +export function useDebouncedValue<T = unknown>( |
| 85 | + value: T, |
| 86 | + debounceTimeMs: number, |
| 87 | +): T { |
| 88 | + const [debouncedValue, setDebouncedValue] = useState(value); |
| 89 | + |
| 90 | + useEffect(() => { |
| 91 | + const timeoutId = window.setTimeout(() => { |
| 92 | + setDebouncedValue(value); |
| 93 | + }, debounceTimeMs); |
| 94 | + |
| 95 | + return () => window.clearTimeout(timeoutId); |
| 96 | + }, [value, debounceTimeMs]); |
| 97 | + |
| 98 | + return debouncedValue; |
| 99 | +} |
0 commit comments