useDebouncedCallbackutilities

useDebouncedCallback

NewSSR SAFE

Creates a debounced version of a callback function with cancellation, flush, and max-wait controls.

$ pnpm dlx shadcn@latest add @byphongphan/use-debounced-callback
Requires @byphongphan in components.json
utilities
Loading preview...

Installation

$ pnpm dlx shadcn@latest add @byphongphan/use-debounced-callback
Requires @byphongphan in components.json

Usage

Debounced Search Input

import { useState } from "react"import { useDebouncedCallback } from "@/shared/hooks"
export function SearchBox() { const [query, setQuery] = useState("")
const debouncedSearch = useDebouncedCallback((searchTerm: string) => { // Perform API call or expensive filter console.log("Searching for:", searchTerm) }, 500)
return ( <input type="text" placeholder="Type to search..." value={query} onChange={(e) => { setQuery(e.target.value) debouncedSearch(e.target.value) }} /> )}

Auto-Save on Blur with flush

import { useEffect, useState } from "react"import { useDebouncedCallback } from "@/shared/hooks"
export function NoteEditor() { const [content, setContent] = useState("")
const saveNote = useDebouncedCallback((text: string) => { saveToDatabase(text) }, 1000, { maxWait: 5000 })
return ( <textarea value={content} onChange={(e) => { setContent(e.target.value) saveNote(e.target.value) }} onBlur={() => { // Immediately save on blur instead of waiting for timer saveNote.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 within maxWait milliseconds 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

ParameterTypeDefaultDescription
callback(...args: TArgs) => void—The target function to debounce.
delaynumber—The debounce delay in milliseconds.
options.leadingbooleanfalseSpecify execution on the leading edge of the timeout.
options.trailingbooleantrueSpecify execution on the trailing edge of the timeout.
options.maxWaitnumber—The maximum time the callback is allowed to wait before execution.

Returns

Returns a debounced function DebouncedFunction<TArgs> with control methods:

Method / PropertyTypeDescription
(...args)(...args: TArgs) => voidInvokes the debounced function with latest arguments.
cancel()() => voidCancels the active timer and discards pending arguments.
flush()() => voidImmediately executes any pending invocation synchronously.
isPending()() => booleanReturns true if a timer is currently active.

Command Palette

Quick search and commands navigation