PerformanceIntermediateSSR-safehooks/performance/useDebouncedCallback.ts

useDebouncedCallback

Debounce a function with cancel and flush.

Import

TypeScript
import { useDebouncedCallback } from '@/hooks';

API

Signature

useDebouncedCallback(fn, delay | options) → fn & { cancel, flush, pending }

When to use

Use useDebouncedCallback instead of re-implementing the same pattern in multiple components.

SSR / Next.js

SSR-safe. Timers and rAF only run after mount / interactions.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useDebouncedCallback
Editor
function Autosave({ onSave }: { onSave: (v: string) => void }) {
  const save = useDebouncedCallback((v: string) => onSave(v), 500);

  return (
    <input
      onChange={(e) => save(e.target.value)}
      onBlur={() => save.flush()}
    />
  );
}
Preview

Implementation source

Full library source for useDebouncedCallback — copy into your project when you are not installing a package yet.

hooks/performance/useDebouncedCallback.ts
import { useEffect, useMemo, useRef } from 'react';
import type { DebounceOptions } from '../types';
import { useLatest } from '../utility/useLatest';
import { useUnmount } from '../utility/useUnmount';

export type DebouncedFunction<TArgs extends unknown[]> = ((
  ...args: TArgs
) => void) & {
  cancel: () => void;
  flush: () => void;
  pending: () => boolean;
};

/**
 * Debounces a callback with leading/trailing/maxWait support.
 * Always cleans up pending timers on unmount or delay change.
 */
export function useDebouncedCallback<TArgs extends unknown[]>(
  fn: (...args: TArgs) => void,
  delayOrOptions: number | DebounceOptions = 300,
): DebouncedFunction<TArgs> {
  const options: DebounceOptions =
    typeof delayOrOptions === 'number'
      ? { delay: delayOrOptions }
      : delayOrOptions;

  const {
    delay = 300,
    leading = false,
    trailing = true,
    maxWait,
  } = options;

  const fnRef = useLatest(fn);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const maxTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const lastArgsRef = useRef<TArgs | null>(null);
  const lastInvokeRef = useRef(0);
  const leadingInvokedRef = useRef(false);

  const clearTimers = () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    if (maxTimerRef.current) {
      clearTimeout(maxTimerRef.current);
      maxTimerRef.current = null;
    }
  };

  const invoke = () => {
    const args = lastArgsRef.current;
    if (!args) return;
    lastArgsRef.current = null;
    lastInvokeRef.current = Date.now();
    leadingInvokedRef.current = false;
    fnRef.current(...args);
  };

  const debounced = useMemo(() => {
    const wrapped = ((...args: TArgs) => {
      lastArgsRef.current = args;
      const now = Date.now();

      if (leading && !leadingInvokedRef.current && !timerRef.current) {
        leadingInvokedRef.current = true;
        lastInvokeRef.current = now;
        fnRef.current(...args);
        lastArgsRef.current = null;
      }

      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }

      timerRef.current = setTimeout(() => {
        timerRef.current = null;
        if (trailing && lastArgsRef.current) {
          invoke();
        }
        leadingInvokedRef.current = false;
        if (maxTimerRef.current) {
          clearTimeout(maxTimerRef.current);
          maxTimerRef.current = null;
        }
      }, delay);

      if (typeof maxWait === 'number' && maxWait > 0 && !maxTimerRef.current) {
        maxTimerRef.current = setTimeout(() => {
          maxTimerRef.current = null;
          if (lastArgsRef.current) {
            if (timerRef.current) {
              clearTimeout(timerRef.current);
              timerRef.current = null;
            }
            invoke();
          }
        }, maxWait);
      }
    }) as DebouncedFunction<TArgs>;

    wrapped.cancel = () => {
      clearTimers();
      lastArgsRef.current = null;
      leadingInvokedRef.current = false;
    };

    wrapped.flush = () => {
      if (lastArgsRef.current) {
        if (timerRef.current) {
          clearTimeout(timerRef.current);
          timerRef.current = null;
        }
        invoke();
      }
      clearTimers();
    };

    wrapped.pending = () => timerRef.current !== null || lastArgsRef.current !== null;

    return wrapped;
    // re-create when timing options change

  }, [delay, leading, trailing, maxWait]);

  useEffect(() => {
    return () => {
      clearTimers();
    };
  }, [delay, leading, trailing, maxWait]);

  useUnmount(() => {
    clearTimers();
  });

  return debounced;
}

Copy-paste example

useDebouncedCallback.example.tsx
'use client';

import { useDebouncedCallback } from '@/hooks';

export function Autosave({ onSave }: { onSave: (v: string) => void }) {
  const save = useDebouncedCallback((v: string) => onSave(v), 500);

  return (
    <input
      onChange={(e) => save(e.target.value)}
      onBlur={() => save.flush()}
    />
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Stable callbacks prevent child re-renders. Always cancel debounce on unmount (handled for you).
  • Source of truth: open hooks/performance/useDebouncedCallback.ts for implementation details