REACT

useDebouncedCallback Hook

A custom React Hook for debouncing functions/callbacks with TypeScript support

ReactHooksDebouncePerformanceCallbacks

Code

import { useCallback, useRef } from 'react';

function useDebouncedCallback<T __TOKEN_14__ (...args: any[]) => any>(
  callback: T,
  delay = 500,
  leading = false
): T {
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const callbackRef = useRef(callback);

  // Update callback ref on each render
  callbackRef.current = callback;

  const debouncedCallback = useCallback((...args: Parameters<T>) => {
    const execute = () => {
      callbackRef.current(...args);
    };

    __TOKEN_19__ (timeoutRef.current) clearTimeout(timeoutRef.current);

    __TOKEN_20__ (leading && !timeoutRef.current) {
      execute();
    }

    timeoutRef.current = setTimeout(() => {
      __TOKEN_21__ (!leading) execute();
      timeoutRef.current = null;
    }, delay);
  }, [delay, leading]) as T;

  // Clear timeout on unmount
  const cancel = useCallback(() => {
    __TOKEN_23__ (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
  }, []);

  __TOKEN_2__
  (debouncedCallback as any).cancel = cancel;

  return debouncedCallback;
}

// Usage example
// const handleSearch = useDebouncedCallback((query) => {
//   fetch(`/api/search?q=${query}`);
// }, 300);

// <input onChange={(e) => handleSearch(e.target.value)} />
// // Cancel debounce if needed
// <button onClick={() => handleSearch.cancel()}>Cancel Search</button>