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

useRateLimitedState.md

139 lines5.0 KB

1---
2id: useRateLimitedState
3title: useRateLimitedState
4---
5​
6```ts
7function useRateLimitedState<TValue, TSelected>(
8 value,
9 options,
10 selector?): [TValue, Dispatch<SetStateAction<TValue>>, ReactRateLimiter<Dispatch<SetStateAction<TValue>>, TSelected>];
11```
12​
13Defined in: [rate-limiter/useRateLimitedState.ts:107](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/rate-limiter/useRateLimitedState.ts#L107)
14​
15A React hook that creates a rate-limited state value that enforces a hard limit on state updates within a time window.
16This hook combines React's useState with rate limiting functionality to provide controlled state updates.
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- useThrottledState: When you want consistent spacing between updates (e.g. UI changes)
30- useDebouncedState: 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 state value
36- A rate-limited setter function that respects the configured limits
37- The rateLimiter instance for additional control
38​
39For more direct control over rate limiting without state management,
40consider using the lower-level useRateLimiter hook instead.
41​
42## State Management and Selector
43​
44The hook uses TanStack Store for reactive state management via the underlying rate limiter instance.
45The `selector` parameter allows you to specify which rate limiter state changes will trigger a re-render,
46optimizing performance by preventing unnecessary re-renders when irrelevant state changes occur.
47​
48**By default, there will be no reactive state subscriptions** and you must opt-in to state
49tracking by providing a selector function. This prevents unnecessary re-renders and gives you
50full control over when your component updates. Only when you provide a selector will the
51component re-render when the selected state values change.
52​
53Available rate limiter state properties:
54- `executionCount`: Number of function executions that have been completed
55- `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
56- `rejectionCount`: Number of function executions that have been rejected due to rate limiting
57​
58## Type Parameters
59​
60### TValue
61​
62`TValue`
63​
64### TSelected
65​
66`TSelected` = `RateLimiterState`
67​
68## Parameters
69​
70### value
71​
72`TValue`
73​
74### options
75​
76[`ReactRateLimiterOptions`](../interfaces/ReactRateLimiterOptions.md)\<`Dispatch`\<`SetStateAction`\<`TValue`\>\>, `TSelected`\>
77​
78### selector?
79​
80(`state`) => `TSelected`
81​
82## Returns
83​
84\[`TValue`, `Dispatch`\<`SetStateAction`\<`TValue`\>\>, [`ReactRateLimiter`](../interfaces/ReactRateLimiter.md)\<`Dispatch`\<`SetStateAction`\<`TValue`\>\>, `TSelected`\>\]
85​
86## Example
87​
88```tsx
89// Default behavior - no reactive state subscriptions
90const [value, setValue, rateLimiter] = useRateLimitedState(0, {
91 limit: 5,
92 window: 60000,
93 windowType: 'sliding'
94});
95​
96// Opt-in to re-render when execution count changes (optimized for tracking successful updates)
97const [value, setValue, rateLimiter] = useRateLimitedState(
98 0,
99 { limit: 5, window: 60000, windowType: 'sliding' },
100 (state) => ({ executionCount: state.executionCount })
101);
102​
103// Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
104const [value, setValue, rateLimiter] = useRateLimitedState(
105 0,
106 { limit: 5, window: 60000, windowType: 'sliding' },
107 (state) => ({ rejectionCount: state.rejectionCount })
108);
109​
110// Opt-in to re-render when execution times change (optimized for window calculations)
111const [value, setValue, rateLimiter] = useRateLimitedState(
112 0,
113 { limit: 5, window: 60000, windowType: 'sliding' },
114 (state) => ({ executionTimes: state.executionTimes })
115);
116​
117// With rejection callback and fixed window
118const [value, setValue] = useRateLimitedState(0, {
119 limit: 3,
120 window: 5000,
121 windowType: 'fixed',
122 onReject: (rateLimiter) => {
123 alert(`Rate limit reached. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
124 }
125});
126​
127// Access rateLimiter methods if needed
128const handleSubmit = () => {
129 const remaining = rateLimiter.getRemainingInWindow();
130 if (remaining > 0) {
131 setValue(newValue);
132 } else {
133 showRateLimitWarning();
134 }
135};
136​
137// Access the selected rate limiter state (will be empty object {} unless selector provided)
138const { executionCount, rejectionCount } = rateLimiter.state;
139```