useDebouncedCallbackutilities
useDebouncedCallback
NewSSR SAFECreates a debounced version of a callback function with cancellation, flush, and max-wait controls.
$ pnpm dlx shadcn@latest add @byphongphan/use-debounced-callbackRequires
@byphongphan in components.jsonuse-debounced-callback.tsx
Loading preview...
Installation
$ pnpm dlx shadcn@latest add @byphongphan/use-debounced-callbackRequires
@byphongphan in components.jsonUsage
Debounced Search Input
Auto-Save on Blur with flush
Features
- No Stale Closures: Uses an internal callback ref to access the latest component props and state without triggering re-attachments.
- Leading & Trailing Triggers: Configure execution at the beginning (
leading: true) or end (trailing: true) of the timeout window. - Max Delay Cap (
maxWait): Guarantees the callback runs at least once withinmaxWaitmilliseconds even under continuous user input. - Execution Controls: Includes
.cancel()to discard pending calls,.flush()to execute immediately, and.isPending()to check active status. - Unmount Safety: Automatically cancels all pending timers when the component unmounts.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
callback | (...args: TArgs) => void | — | The target function to debounce. |
delay | number | — | The debounce delay in milliseconds. |
options.leading | boolean | false | Specify execution on the leading edge of the timeout. |
options.trailing | boolean | true | Specify execution on the trailing edge of the timeout. |
options.maxWait | number | — | The maximum time the callback is allowed to wait before execution. |
Returns
Returns a debounced function DebouncedFunction<TArgs> with control methods:
| Method / Property | Type | Description |
|---|---|---|
(...args) | (...args: TArgs) => void | Invokes the debounced function with latest arguments. |
cancel() | () => void | Cancels the active timer and discards pending arguments. |
flush() | () => void | Immediately executes any pending invocation synchronously. |
isPending() | () => boolean | Returns true if a timer is currently active. |