useDebouncedValue and useDebouncedCallback

Two React hooks for debouncing. useDebouncedValue returns a value once it has stopped changing for a delay, so you can compare it with the live value to show a pending state. useDebouncedCallback returns a stable function with cancel, flush and isPending; it always calls your latest callback, supports leading calls and a maxWait cap, and cancels on unmount. The preview filters a list while showing the debouncing state and autosaves a note.

Forms & inputsHookTailwind v4

Source

import * as React from "react";

export interface DebounceOptions {
  /** Also run on the first call of a burst, then wait out the delay. */
  leading?: boolean;
  /** Longest time a burst of calls can postpone a run, in ms. */
  maxWait?: number;
}

export interface DebouncedFunction<A extends unknown[]> {
  (...args: A): void;
  /** Drops the pending call. */
  cancel(): void;
  /** Runs the pending call now. */
  flush(): void;
  /** True while a call is waiting to run. */
  isPending(): boolean;
}

// useLayoutEffect warns during server rendering; fall back to useEffect there.
const useIsomorphicLayoutEffect = typeof window === "undefined" ? React.useEffect : React.useLayoutEffect;

/**
 * Returns a stable function that runs `callback` once calls stop for `delay` ms.
 * Always calls the latest `callback`, and cancels itself on unmount.
 */
export function useDebouncedCallback<A extends unknown[]>(
  callback: (...args: A) => void,
  delay = 300,
  { leading = false, maxWait }: DebounceOptions = {},
): DebouncedFunction<A> {
  const callbackRef = React.useRef(callback);
  useIsomorphicLayoutEffect(() => {
    callbackRef.current = callback;
  });

  const debounced = React.useMemo(() => {
    let timer: ReturnType<typeof setTimeout> | undefined;
    let maxTimer: ReturnType<typeof setTimeout> | undefined;
    let pending: A | null = null;

    const run = () => {
      const args = pending;
      pending = null;
      if (args) callbackRef.current(...args);
    };
    const clear = () => {
      if (timer !== undefined) clearTimeout(timer);
      if (maxTimer !== undefined) clearTimeout(maxTimer);
      timer = maxTimer = undefined;
    };
    const trailing = () => {
      clear();
      run();
    };

    const fn = ((...args: A) => {
      pending = args;
      if (leading && timer === undefined) {
        run();
        timer = setTimeout(trailing, delay);
        return;
      }
      if (timer !== undefined) clearTimeout(timer);
      timer = setTimeout(trailing, delay);
      if (maxWait !== undefined && maxTimer === undefined) {
        maxTimer = setTimeout(() => {
          maxTimer = undefined;
          run();
        }, maxWait);
      }
    }) as DebouncedFunction<A>;

    fn.cancel = () => {
      clear();
      pending = null;
    };
    fn.flush = () => {
      clear();
      run();
    };
    fn.isPending = () => pending !== null;
    return fn;
  }, [delay, leading, maxWait]);

  React.useEffect(() => () => debounced.cancel(), [debounced]);
  return debounced;
}

/**
 * Returns `value` once it has stopped changing for `delay` ms.
 * Compare the two to show a pending state: `const pending = value !== debounced`.
 */
export function useDebouncedValue<T>(value: T, delay = 300, options: DebounceOptions = {}): T {
  const [debounced, setDebounced] = React.useState(value);
  const update = useDebouncedCallback((next: T) => setDebounced(() => next), delay, options);
  React.useEffect(() => {
    update(value);
  }, [value, update]);
  return debounced;
}