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

useThrottledCallback

Function: useThrottledCallback()

ts
function useThrottledCallback<TFn, TArgs>(fn, options): (...args) => void
function useThrottledCallback<TFn, TArgs>(fn, options): (...args) => void

Defined in: react-pacer/src/throttler/useThrottledCallback.ts:42

A React hook that creates a throttled version of a callback function. This hook is essentially a wrapper around the basic throttle function that is exported from @tanstack/pacer, but optimized for React with reactive options and a stable function reference.

The throttled function will execute at most once within the specified wait time period, regardless of how many times it is called. If called multiple times during the wait period, only the first invocation will execute, and subsequent calls will be ignored until the wait period has elapsed.

This hook provides a simpler API compared to useThrottler, making it ideal for basic throttling needs. However, it does not expose the underlying Throttler instance.

For advanced usage requiring features like:

  • Manual cancellation
  • Access to execution counts
  • Custom useCallback dependencies

Consider using the useThrottler hook instead.

Type Parameters

TFn extends (...args) => any

TArgs extends any[]

Parameters

fn

TFn

options

ThrottlerOptions

Returns

Function

Parameters

args

...TArgs

Returns

void

Example

tsx
// Throttle a window resize handler
const handleResize = useThrottledCallback(() => {
  updateLayoutMeasurements();
}, {
  wait: 100 // Execute at most once every 100ms
});

// Use in an event listener
useEffect(() => {
  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, [handleResize]);
// Throttle a window resize handler
const handleResize = useThrottledCallback(() => {
  updateLayoutMeasurements();
}, {
  wait: 100 // Execute at most once every 100ms
});

// Use in an event listener
useEffect(() => {
  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, [handleResize]);
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.