Skip to content

useDebounce

useDebounce is a React hook that returns a debounced version of the provided callback function. It helps optimize event handling by delaying function execution and grouping multiple calls into one.

Interface

ts
function useDebounce<F extends (...args: any[]) => unknown>(
  callback: F,
  wait: number,
  options: DebounceOptions
): F & { cancel: () => void };

Parameters

  • callbackrequired · F

    The function to debounce.

  • waitrequired · number

    The number of milliseconds to delay the function execution.

  • optionsDebounceOptions

    Configuration options for debounce behavior.

    • options.leadingboolean · false

      If true, the function is called at the start of the sequence.

    • options.trailingboolean · true

      If true, the function is called at the end of the sequence.

Return Value

  • F & { cancel: () => void }

    debounced function that delays invoking the callback. It also includes a cancel method to cancel any pending debounced execution.

Example

tsx
function SearchInput() {
  const [query, setQuery] = useState('');

  const debouncedSearch = useDebounce((value: string) => {
    // Actual API call
    searchAPI(value);
  }, 300);

  return (
    <input
      value={query}
      onChange={e => {
        setQuery(e.target.value);
        debouncedSearch(e.target.value);
      }}
      placeholder="Enter search term"
    />
  );
}

Released under the MIT License.