|
| 1 | +import { useCallback, useEffect, useRef } from "react"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Creates a debounced version of a callback function that delays invoking the function |
| 5 | + * until after the specified delay has elapsed since the last time it was invoked. |
| 6 | + * |
| 7 | + * This hook is useful for optimizing performance by limiting the rate at which a function |
| 8 | + * can fire, particularly useful for: |
| 9 | + * - Search input handlers |
| 10 | + * - Auto-save functionality |
| 11 | + * - API calls triggered by user input |
| 12 | + * - Window resize/scroll handlers |
| 13 | + * |
| 14 | + * @example |
| 15 | + * const debouncedSearch = useDebouncedCallback((query: string) => { |
| 16 | + * fetchSearchResults(query); |
| 17 | + * }, 500); |
| 18 | + * |
| 19 | + * // Will only execute after user stops typing for 500ms |
| 20 | + * debouncedSearch(inputValue); |
| 21 | + */ |
| 22 | +const useDebouncedFn = <T extends (...args: never[]) => unknown>(callback: T, delay = 300): ((...args: Parameters<T>) => void) => { |
| 23 | + // Store the latest callback to avoid stale closures |
| 24 | + const callbackRef = useRef(callback); |
| 25 | + callbackRef.current = callback; |
| 26 | + |
| 27 | + // Store the timeout ID for cleanup |
| 28 | + const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null); |
| 29 | + |
| 30 | + // Create the debounced function (only recreates if delay changes) |
| 31 | + const debouncedCallback = useCallback( |
| 32 | + (...args: Parameters<T>) => { |
| 33 | + // Clear any existing timeout |
| 34 | + if (timeoutRef.current !== null) { |
| 35 | + clearTimeout(timeoutRef.current); |
| 36 | + } |
| 37 | + |
| 38 | + // Set a new timeout to execute the callback after the delay |
| 39 | + timeoutRef.current = setTimeout(() => { |
| 40 | + callbackRef.current(...args); |
| 41 | + }, delay); |
| 42 | + }, |
| 43 | + [delay], |
| 44 | + ); |
| 45 | + |
| 46 | + // Cleanup: clear timeout when component unmounts |
| 47 | + useEffect(() => { |
| 48 | + return () => { |
| 49 | + if (timeoutRef.current !== null) { |
| 50 | + clearTimeout(timeoutRef.current); |
| 51 | + } |
| 52 | + }; |
| 53 | + }, []); |
| 54 | + |
| 55 | + return debouncedCallback; |
| 56 | +}; |
| 57 | + |
| 58 | +export default useDebouncedFn; |
0 commit comments