useDebouncedCallback
A custom hook for creating debounced functions in React.
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.
Loading...
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
Textends(...args: any[]) => any- The type of the callback function to debounce.
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | T | The function to debounce. |
delay | number | The delay in milliseconds before executing the callback. Default is 300. |
options | DebounceOptions | Optional configuration for debounce behavior. |
Options Object
| Option | Type | Description | Default |
|---|---|---|---|
leading | boolean | Whether to execute the function on the leading edge (first call). | false |
trailing | boolean | Whether to execute the function on the trailing edge (after delay). | true |
maxWait | number | Maximum 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 functioncancel(): Cancels any pending executions of the debounced functionflush(): Immediately executes any pending function callisPending(): Returnstrueif a function call is waiting to be executed