use-debounce.ts1.2 KBView on GitHub
import { useCallback, useEffect, useRef, useState } from 'react';

export const useDebounce = <T extends (...args: any[]) => any>(callback: T, delay: number): T => {
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const debouncedCallback = useCallback(
    (...args: Parameters<T>) => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }

      timeoutRef.current = setTimeout(() => {
        callback(...args);
        timeoutRef.current = null;
      }, delay);
    },
    [callback, delay],
  ) as T;

  return debouncedCallback;
};

/**
 * The value flavour: `value`, but only after it has stopped changing for `delay`.
 *
 * For the read side of a search box, where `useDebounce` (which wraps a callback)
 * does not fit — a query key cannot be debounced by wrapping the setter without
 * also making the input itself lag a keystroke behind the caret.
 */
export const useDebouncedValue = <T,>(value: T, delay: number): T => {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const timeout = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(timeout);
  }, [value, delay]);

  return debounced;
};