Typed HooksGetting StarteduseDebouncedCallback

useDebouncedCallback

A custom hook for creating debounced functions in React.

⚠️ This content is not available in your language yet.

useDebouncedCallback is a powerful custom React hook that creates a debounced version of a callback function, preventing excessive function calls in scenarios like search inputs, window resizing, or handling rapid user interactions.

Unlike traditional debounce utilities, this hook is specifically designed for React's lifecycle and includes additional control functions for managing the debounced state. It also properly handles changes to the callback function reference through React's renders.

Idle
500ms
None
Empty
Empty

Installation

pnpm dlx shadcn@latest add https://shaddy-docs.vercel.app/r/use-debounced-callback

API

useDebouncedCallback<T>(callback: T, delay: number, options?: DebounceOptions): DebouncedFunction<T>

Type Parameters

  • T extends (...args: any[]) => any - The type of the callback function to debounce.

Parameters

ParameterTypeDescription
callbackTThe function to debounce.
delaynumberThe delay in milliseconds before executing the callback. Default is 300.
optionsDebounceOptionsOptional configuration for debounce behavior.

Options Object

OptionTypeDescriptionDefault
leadingbooleanWhether to execute the function on the leading edge (first call).false
trailingbooleanWhether to execute the function on the trailing edge (after delay).true
maxWaitnumberMaximum time to wait before forcing execution, even with continued calls.undefined

Returns

Returns a debounced function with attached control methods:

  • (...args: Parameters<T>): The debounced function to call with the same arguments as the original function
  • cancel(): Cancels any pending executions of the debounced function
  • flush(): Immediately executes any pending function call
  • isPending(): Returns true if a function call is waiting to be executed