Framework
Version
防抖器 API 參考
節流器 API 參考
速率限制器 API 參考
佇列 API 參考

useThrottler

Function: useThrottler()

ts
function useThrottler<TFn>(fn, options): Throttler<TFn>
function useThrottler<TFn>(fn, options): Throttler<TFn>

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

A low-level React hook that creates a Throttler instance that limits how often the provided function can execute.

This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that integrates directly with React's useState, see useThrottledState.

Throttling ensures a function executes at most once within a specified time window, regardless of how many times it is called. This is useful for rate-limiting expensive operations or UI updates.

Type Parameters

TFn extends AnyFunction

Parameters

fn

TFn

options

ThrottlerOptions<TFn>

Returns

Throttler<TFn>

Example

tsx
// Basic throttling with custom state
const [value, setValue] = useState(0);
const throttler = useThrottler(setValue, { wait: 1000 });

// With Redux
const dispatch = useDispatch();
const throttler = useThrottler(
  (value) => dispatch(updateAction(value)),
  { wait: 1000 }
);

// With any state manager
const throttler = useThrottler(
  (value) => stateManager.setState(value),
  {
    wait: 2000,
    leading: true,   // Execute immediately on first call
    trailing: false  // Skip trailing edge updates
  }
);
// Basic throttling with custom state
const [value, setValue] = useState(0);
const throttler = useThrottler(setValue, { wait: 1000 });

// With Redux
const dispatch = useDispatch();
const throttler = useThrottler(
  (value) => dispatch(updateAction(value)),
  { wait: 1000 }
);

// With any state manager
const throttler = useThrottler(
  (value) => stateManager.setState(value),
  {
    wait: 2000,
    leading: true,   // Execute immediately on first call
    trailing: false  // Skip trailing edge updates
  }
);
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.