Open History to see the last commit
1---
2id: useThrottler
3title: useThrottler
4---
5
6```ts
7function useThrottler<TFn, TSelected>(
8 fn,
9 options,
10selector?): ReactThrottler<TFn, TSelected>;
11```
12
13Defined in: [throttler/useThrottler.ts:168](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/throttler/useThrottler.ts#L168)
14
15A low-level React hook that creates a `Throttler` instance that limits how often the provided function can execute.
16
17This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
18you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc). For a simpler and higher-level hook that
19integrates directly with React's useState, see useThrottledState.
20
21Throttling ensures a function executes at most once within a specified time window,
22regardless of how many times it is called. This is useful for rate-limiting
23expensive operations or UI updates.
24
25## State Management and Selector
26
27The hook uses TanStack Store for reactive state management. You can subscribe to state changes
28in two ways:
29
30**1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
31
32Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
33needing to pass a selector to the hook. This is ideal when you want to subscribe to state
34in child components.
35
36**2. Using the `selector` parameter (For hook-level subscriptions)**
37
38The `selector` parameter allows you to specify which state changes will trigger a re-render
39at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
40state changes occur.
41
42**By default, there will be no reactive state subscriptions** and you must opt-in to state
43tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
44re-renders and gives you full control over when your component updates.
45
46Available state properties:
47- `executionCount`: Number of function executions that have been completed
48- `lastArgs`: The arguments from the most recent call to maybeExecute
49- `lastExecutionTime`: Timestamp of the last function execution in milliseconds
50- `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
51- `isPending`: Whether the throttler is waiting for the timeout to trigger execution
52- `status`: Current execution status ('disabled' | 'idle' | 'pending')
53
54## Unmount behavior
55
56By default, the hook cancels any pending execution when the component unmounts.
57Use the `onUnmount` option to customize this. For example, to flush pending work instead:
58
59```tsx
60const throttler = useThrottler(fn, {
61 wait: 1000,
62 onUnmount: (t) => t.flush()
63});
64```
65
66## Type Parameters
67
68### TFn
69
70`TFn` *extends* `AnyFunction`
71
72### TSelected
73
74`TSelected` = \{
75\}
76
77## Parameters
78
79### fn
80
81`TFn`
82
83### options
84
85[`ReactThrottlerOptions`](../interfaces/ReactThrottlerOptions.md)\<`TFn`, `TSelected`\>
86
87### selector?
88
89(`state`) => `TSelected`
90
91## Returns
92
93[`ReactThrottler`](../interfaces/ReactThrottler.md)\<`TFn`, `TSelected`\>
94
95## Example
96
97```tsx
98// Default behavior - no reactive state subscriptions
99const [value, setValue] = useState(0);
100const throttler = useThrottler(setValue, { wait: 1000 });
101
102// Subscribe to state changes deep in component tree using Subscribe HOC
103<throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
104 {({ isPending }) => (
105 <div>{isPending ? 'Throttling...' : 'Ready'}</div>
106 )}
107</throttler.Subscribe>
108
109// Opt-in to re-render when execution count changes at hook level (optimized for tracking executions)
110const [value, setValue] = useState(0);
111const throttler = useThrottler(
112 setValue,
113 { wait: 1000 },
114 (state) => ({ executionCount: state.executionCount })
115);
116
117// Opt-in to re-render when throttling state changes (optimized for loading indicators)
118const [value, setValue] = useState(0);
119const throttler = useThrottler(
120 setValue,
121 { wait: 1000 },
122 (state) => ({
123 isPending: state.isPending,
124 status: state.status
125 })
126);
127
128// Opt-in to re-render when timing information changes (optimized for timing displays)
129const [value, setValue] = useState(0);
130const throttler = useThrottler(
131 setValue,
132 { wait: 1000 },
133 (state) => ({
134 lastExecutionTime: state.lastExecutionTime,
135 nextExecutionTime: state.nextExecutionTime
136 })
137);
138
139// With any state manager
140const throttler = useThrottler(
141 (value) => stateManager.setState(value),
142 {
143 wait: 2000,
144 leading: true, // Execute immediately on first call
145 trailing: false // Skip trailing edge updates
146 }
147);
148
149// Access the selected state (will be empty object {} unless selector provided)
150const { executionCount, isPending } = throttler.state;
151```