Framework
Version
Debouncer API Reference
Throttler API Reference
Rate Limiter API Reference
Queue API Reference

useDebouncer

Function: useDebouncer()

ts
function useDebouncer<TFn, TArgs>(fn, options): object
function useDebouncer<TFn, TArgs>(fn, options): object

Defined in: react-pacer/src/debouncer/useDebouncer.ts:37

A React hook that creates and manages a Debouncer instance.

This is a lower-level hook that provides direct access to the Debouncer's functionality without any built-in state management. This allows you to integrate it with any state management solution you prefer (useState, Redux, Zustand, etc.).

This hook provides debouncing functionality to limit how often a function can be called, waiting for a specified delay before executing the latest call. This is useful for handling frequent events like window resizing, scroll events, or real-time search inputs.

The debouncer will only execute the function after the specified wait time has elapsed since the last call. If the function is called again before the wait time expires, the timer resets and starts waiting again.

Type Parameters

TFn extends (...args) => any

TArgs extends any[]

Parameters

fn

TFn

options

DebouncerOptions

Returns

object

cancel()

ts
readonly cancel: () => void;
readonly cancel: () => void;

Cancels any pending execution

Returns

void

getExecutionCount()

ts
readonly getExecutionCount: () => number;
readonly getExecutionCount: () => number;

Returns the number of times the function has been executed

Returns

number

maybeExecute()

ts
readonly maybeExecute: (...args) => void;
readonly maybeExecute: (...args) => void;

Attempts to execute the debounced function If a call is already in progress, it will be queued

Parameters

args

...TArgs

Returns

void

Example

tsx
// Debounce a search function to limit API calls
const searchDebouncer = useDebouncer(
  (query: string) => fetchSearchResults(query),
  { wait: 500 } // Wait 500ms after last keystroke
);

// In an event handler
const handleChange = (e) => {
  searchDebouncer.maybeExecute(e.target.value);
};

// Get number of times the debounced function has executed
const executionCount = searchDebouncer.getExecutionCount();
// Debounce a search function to limit API calls
const searchDebouncer = useDebouncer(
  (query: string) => fetchSearchResults(query),
  { wait: 500 } // Wait 500ms after last keystroke
);

// In an event handler
const handleChange = (e) => {
  searchDebouncer.maybeExecute(e.target.value);
};

// Get number of times the debounced function has executed
const executionCount = searchDebouncer.getExecutionCount();
Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.