Skip to content
Source
Sign inSign up
TanStack/pacer
Open History to see the last commit

throttling.md

191 lines7.6 KB

1---
2title: React Throttling Guide
3id: throttling
4---
5​
6Throttling limits how often a function can execute while calls continue to arrive. Unlike debouncing, throttling does not wait for activity to stop. It creates a bounded execution interval that works well for continuous events and updates.
7​
8With the default settings, the first call executes immediately. Calls received during the wait period are consolidated into one trailing execution that uses the latest arguments.
9​
10## How throttling works
11​
12The timeline below shows a throttler that allows one execution every three ticks:
13​
14```text
15Throttling (one execution per 3 ticks)
16Timeline: [1 second per tick]
17Calls: ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️
18Executed: ✅ ❌ ⏳ -> ✅ ❌ ❌ ❌ ✅ ✅
19 [================================================================]
20 ^ At most one execution per interval
21​
22 [First burst] [More calls] [Spaced calls]
23 Execute first Keep latest trailing Execute when allowed
24```
25​
26Calls may be discarded, but execution continues at a predictable interval while activity is ongoing.
27​
28## When to use throttling
29​
30Choose throttling when:
31​
32- Work should continue while events are arriving.
33- Executions should be spaced by a minimum interval.
34- Intermediate calls may be discarded.
35- Immediate feedback from the first call is useful.
36​
37Choose another utility when:
38​
39- Work should wait until activity stops. Use [debouncing](./debouncing.md).
40- A specific number of calls may run within a window. Use [rate limiting](./rate-limiting.md).
41- Every operation must eventually run. Use [queuing](./queuing.md).
42- Several items should run together. Use [batching](./batching.md).
43- You need Promise results, retries, or abort support. Use [async throttling](./async-throttling.md).
44​
45## Choose an API
46​
47- `useThrottledCallback` for a stable throttled event handler
48- `useThrottledState` or `useThrottledValue` for throttled React state
49- `useThrottler` for lifecycle methods and selected state
50​
51Use the callback API for event handlers, the state or value API for rate-controlled UI state, and the instance API for lifecycle methods and timing state.
52​
53## React example
54​
55```tsx
56import { useThrottledCallback, useThrottledValue } from '@tanstack/react-pacer'
57​
58function ScrollStatus({ position }: { position: number }) {
59 const report = useThrottledCallback(sendPosition, { wait: 250 })
60 const [displayedPosition] = useThrottledValue(position, { wait: 100 })
61​
62 return (
63 <button onClick={() => report(position)}>Report {displayedPosition}</button>
64 )
66```
67​
68The focused snippets later in this guide use `useThrottler` and assume they run inside a component or another hook.
69​
70## Execution timing
71​
72The `leading` and `trailing` options control which edges of the throttle interval may execute.
73​
74| `leading` | `trailing` | Behavior |
75| --------- | ---------- | ------------------------------------------------------------------------------------------------------------ |
76| `true` | `true` | Execute the first call immediately and the latest blocked call at the trailing edge. This is the default. |
77| `true` | `false` | Execute immediately when allowed and discard calls during the interval. |
78| `false` | `true` | Delay the first execution until the trailing edge and use the latest arguments received during the interval. |
79| `false` | `false` | Do not execute any calls. |
80​
81```ts
82const throttler = useThrottler(updateProgress, {
83 wait: 1000,
84 leading: true,
85 trailing: true,
86})
87​
88throttler.maybeExecute(10) // Executes immediately.
89throttler.maybeExecute(20)
90throttler.maybeExecute(30) // Executes at the trailing edge with 30.
91```
92​
93Calls received during an existing interval update the trailing arguments without restarting that interval. This is the central difference from debouncing.
94​
95## Controlling pending work
96​
97### Flush
98​
99`flush()` immediately executes the pending trailing call. It does nothing when no trailing call is pending.
100​
101```ts
102throttler.maybeExecute(10) // Leading execution.
103throttler.maybeExecute(20) // Pending trailing execution.
104throttler.flush() // Executes with 20 now.
105```
106​
107### Cancel
108​
109`cancel()` discards the pending trailing call and clears its stored arguments. It does not reset the timing of the most recent completed execution.
110​
111```ts
112throttler.maybeExecute(20)
113throttler.cancel()
114```
115​
116### Reset
117​
118`reset()` restores state counters and timing values to their defaults. It does not clear an already scheduled timeout. Call `cancel()` before `reset()` when pending work must be discarded.
119​
120```ts
121throttler.cancel()
122throttler.reset()
123```
124​
125## Configuring behavior at runtime
126​
127Use `setOptions()` to update options after construction:
128​
129```ts
130throttler.setOptions({
131 wait: 250,
132 trailing: false,
133})
134```
135​
136A changed `wait` value does not reschedule an existing trailing timeout. It applies to later scheduling and executions.
137​
138The `enabled` and `wait` options may be functions that receive the throttler instance:
139​
140```ts
141const throttler = useThrottler(updateProgress, {
142 enabled: (throttler) => throttler.store.state.executionCount < 100,
143 wait: (throttler) => (throttler.store.state.executionCount < 10 ? 100 : 250),
144})
145```
146​
147Disabling a throttler through `setOptions()` cancels a pending trailing execution.
148​
149### Observing executions
150​
151`onExecute` runs after the wrapped function and receives the executed arguments followed by the throttler instance:
152​
153```ts
154const throttler = useThrottler(updateProgress, {
155 wait: 100,
156 onExecute: (args, throttler) => {
157 console.log('Rendered value:', args[0])
158 console.log('Executions:', throttler.store.state.executionCount)
159 },
160})
161```
162​
163## React lifecycle
164​
165The adapter cancels pending work when its owner is destroyed. Providing `onUnmount` replaces that default cleanup, so a custom callback must perform every required lifecycle action. When custom cleanup flushes work, remember that user callbacks can run while the component is being destroyed.
166​
167## Reactive state
168​
169The adapter subscribes only to the state returned by the selector argument. Without a selector, the adapter state is empty. Create the utility at the top level of a component or another hook and select only fields used by the view:
170​
171```ts
172const throttler = useThrottler(updateProgress, { wait: 100 }, (state) => ({
173 isPending: state.isPending,
174 executionCount: state.executionCount,
175}))
176​
177console.log(throttler.state.isPending, throttler.state.executionCount)
178```
179​
180Option functions and lifecycle callbacks receive the underlying public utility instance. The `.store.state` reads inside those callbacks in the examples above are supported. Rendering code should read the selected adapter state shown here.
181​
182To restore selected state that your app has persisted, pass a partial snapshot through `initialState`. It is merged with the defaults. Restore only durable fields. Pending timers are not restored.
183​
184- `isPending`: Whether a trailing execution is waiting.
185- `lastArgs`: The arguments retained for a possible trailing execution.
186- `lastExecutionTime`: When the wrapped function last executed.
187- `nextExecutionTime`: When another execution can occur.
188- `executionCount`: How many times the wrapped function has executed.
189- `status`: `'disabled'`, `'idle'`, or `'pending'`.
190​
191See the [React API reference](../reference/index.md) for adapter signatures and the public core reference for complete option and state types.