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

useRateLimitedValue.md

128 lines4.8 KB

1---
2id: useRateLimitedValue
3title: useRateLimitedValue
4---
5​
6```ts
7function useRateLimitedValue<TValue, TSelected>(
8 value,
9 options,
10 selector?): [TValue, ReactRateLimiter<Dispatch<SetStateAction<TValue>>, TSelected>];
11```
12​
13Defined in: [rate-limiter/useRateLimitedValue.ts:96](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/rate-limiter/useRateLimitedValue.ts#L96)
14​
15A high-level React hook that creates a rate-limited version of a value that updates at most a certain number of times within a time window.
16This hook uses React's useState internally to manage the rate-limited state.
17​
18Rate limiting is a simple "hard limit" approach - it allows all updates until the limit is reached, then blocks
19subsequent updates until the window resets. Unlike throttling or debouncing, it does not attempt to space out
20or intelligently collapse updates. This can lead to bursts of rapid updates followed by periods of no updates.
21​
22The rate limiter supports two types of windows:
23- 'fixed': A strict window that resets after the window period. All updates within the window count
24 towards the limit, and the window resets completely after the period.
25- 'sliding': A rolling window that allows updates as old ones expire. This provides a more
26 consistent rate of updates over time.
27​
28For smoother update patterns, consider:
29- useThrottledValue: When you want consistent spacing between updates (e.g. UI changes)
30- useDebouncedValue: When you want to collapse rapid updates into a single update (e.g. search input)
31​
32Rate limiting should primarily be used when you need to enforce strict limits, like API rate limits.
33​
34The hook returns a tuple containing:
35- The rate-limited value that updates according to the configured rate limit
36- The rate limiter instance with control methods
37​
38For more direct control over rate limiting behavior without React state management,
39consider using the lower-level useRateLimiter hook instead.
40​
41## State Management and Selector
42​
43The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.
44The `selector` parameter allows you to specify which rate limiter state changes will trigger a re-render,
45optimizing performance by preventing unnecessary re-renders when irrelevant state changes occur.
46​
47**By default, there will be no reactive state subscriptions** and you must opt-in to state
48tracking by providing a selector function. This prevents unnecessary re-renders and gives you
49full control over when your component updates. Only when you provide a selector will the
50component re-render when the selected state values change.
51​
52Available rate limiter state properties:
53- `executionCount`: Number of function executions that have been completed
54- `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
55- `rejectionCount`: Number of function executions that have been rejected due to rate limiting
56​
57## Type Parameters
58​
59### TValue
60​
61`TValue`
62​
63### TSelected
64​
65`TSelected` = `RateLimiterState`
66​
67## Parameters
68​
69### value
70​
71`TValue`
72​
73### options
74​
75[`ReactRateLimiterOptions`](../interfaces/ReactRateLimiterOptions.md)\<`Dispatch`\<`SetStateAction`\<`TValue`\>\>, `TSelected`\>
76​
77### selector?
78​
79(`state`) => `TSelected`
80​
81## Returns
82​
83\[`TValue`, [`ReactRateLimiter`](../interfaces/ReactRateLimiter.md)\<`Dispatch`\<`SetStateAction`\<`TValue`\>\>, `TSelected`\>\]
84​
85## Example
86​
87```tsx
88// Default behavior - no reactive state subscriptions
89const [rateLimitedValue, rateLimiter] = useRateLimitedValue(rawValue, {
90 limit: 5,
91 window: 60000,
92 windowType: 'sliding'
93});
94​
95// Opt-in to re-render when execution count changes (optimized for tracking successful updates)
96const [rateLimitedValue, rateLimiter] = useRateLimitedValue(
97 rawValue,
98 { limit: 5, window: 60000, windowType: 'sliding' },
99 (state) => ({ executionCount: state.executionCount })
100);
101​
102// Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
103const [rateLimitedValue, rateLimiter] = useRateLimitedValue(
104 rawValue,
105 { limit: 5, window: 60000, windowType: 'sliding' },
106 (state) => ({ rejectionCount: state.rejectionCount })
107);
108​
109// Opt-in to re-render when execution times change (optimized for window calculations)
110const [rateLimitedValue, rateLimiter] = useRateLimitedValue(
111 rawValue,
112 { limit: 5, window: 60000, windowType: 'sliding' },
113 (state) => ({ executionTimes: state.executionTimes })
114);
115​
116// With rejection callback and fixed window
117const [rateLimitedValue, rateLimiter] = useRateLimitedValue(rawValue, {
118 limit: 3,
119 window: 5000,
120 windowType: 'fixed',
121 onReject: (rateLimiter) => {
122 console.log(`Update rejected. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
123 }
124});
125​
126// Access the selected rate limiter state (will be empty object {} unless selector provided)
127const { executionCount, rejectionCount } = rateLimiter.state;
128```