Open History to see the last commit
1---
2id: useRateLimiter
3title: useRateLimiter
4---
5
6```ts
7function useRateLimiter<TFn, TSelected>(
8 fn,
9 options,
10selector?): PreactRateLimiter<TFn, TSelected>;
11```
12
13Defined in: [rate-limiter/useRateLimiter.ts:190](https://github.com/TanStack/pacer/blob/main/packages/preact-pacer/src/rate-limiter/useRateLimiter.ts#L190)
14
15A low-level Preact hook that creates a `RateLimiter` instance to enforce rate limits on function execution.
16
17This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
18you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
19
20Rate limiting is a simple "hard limit" approach that allows executions until a maximum count is reached within
21a time window, then blocks all subsequent calls until the window resets. Unlike throttling or debouncing,
22it does not attempt to space out or collapse executions intelligently.
23
24The rate limiter supports two types of windows:
25- 'fixed': A strict window that resets after the window period. All executions within the window count
26 towards the limit, and the window resets completely after the period.
27- 'sliding': A rolling window that allows executions as old ones expire. This provides a more
28 consistent rate of execution over time.
29
30For smoother execution patterns:
31- Use throttling when you want consistent spacing between executions (e.g. UI updates)
32- Use debouncing when you want to collapse rapid-fire events (e.g. search input)
33- Use rate limiting only when you need to enforce hard limits (e.g. API rate limits)
34
35## State Management and Selector
36
37The hook uses TanStack Store for reactive state management. You can subscribe to state changes
38in two ways:
39
40**1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
41
42Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
43needing to pass a selector to the hook. This is ideal when you want to subscribe to state
44in child components.
45
46**2. Using the `selector` parameter (For hook-level subscriptions)**
47
48The `selector` parameter allows you to specify which state changes will trigger a re-render
49at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
50state changes occur.
51
52**By default, there will be no reactive state subscriptions** and you must opt-in to state
53tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
54re-renders and gives you full control over when your component updates.
55
56Available state properties:
57- `executionCount`: Number of function executions that have been completed
58- `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
59- `rejectionCount`: Number of function executions that have been rejected due to rate limiting
60
61The hook returns an object containing:
62- maybeExecute: The rate-limited function that respects the configured limits
63- getExecutionCount: Returns the number of successful executions
64- getRejectionCount: Returns the number of rejected executions due to rate limiting
65- getRemainingInWindow: Returns how many more executions are allowed in the current window
66- reset: Resets the execution counts and window timing
67
68## Type Parameters
69
70### TFn
71
72`TFn` *extends* `AnyFunction`
73
74### TSelected
75
76`TSelected` = \{
77\}
78
79## Parameters
80
81### fn
82
83`TFn`
84
85### options
86
87[`PreactRateLimiterOptions`](../interfaces/PreactRateLimiterOptions.md)\<`TFn`, `TSelected`\>
88
89### selector?
90
91(`state`) => `TSelected`
92
93## Returns
94
95[`PreactRateLimiter`](../interfaces/PreactRateLimiter.md)\<`TFn`, `TSelected`\>
96
97## Example
98
99```tsx
100// Default behavior - no reactive state subscriptions
101const rateLimiter = useRateLimiter(apiCall, {
102 limit: 5,
103 window: 60000,
104 windowType: 'sliding',
105});
106
107// Subscribe to state changes deep in component tree using Subscribe HOC
108<rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
109 {({ rejectionCount }) => (
110 <div>Rejections: {rejectionCount}</div>
111 )}
112</rateLimiter.Subscribe>
113
114// Opt-in to re-render when execution count changes at hook level (optimized for tracking successful executions)
115const rateLimiter = useRateLimiter(
116 apiCall,
117 {
118 limit: 5,
119 window: 60000,
120 windowType: 'sliding',
121 },
122 (state) => ({ executionCount: state.executionCount })
123);
124
125// Opt-in to re-render when rejection count changes (optimized for tracking rate limit violations)
126const rateLimiter = useRateLimiter(
127 apiCall,
128 {
129 limit: 5,
130 window: 60000,
131 windowType: 'sliding',
132 },
133 (state) => ({ rejectionCount: state.rejectionCount })
134);
135
136// Opt-in to re-render when execution times change (optimized for window calculations)
137const rateLimiter = useRateLimiter(
138 apiCall,
139 {
140 limit: 5,
141 window: 60000,
142 windowType: 'sliding',
143 },
144 (state) => ({ executionTimes: state.executionTimes })
145);
146
147// Multiple state properties - re-render when any of these change
148const rateLimiter = useRateLimiter(
149 apiCall,
150 {
151 limit: 5,
152 window: 60000,
153 windowType: 'sliding',
154 },
155 (state) => ({
156 executionCount: state.executionCount,
157 rejectionCount: state.rejectionCount
158 })
159);
160
161// Monitor rate limit status
162const handleClick = () => {
163 const remaining = rateLimiter.getRemainingInWindow();
164 if (remaining > 0) {
165 rateLimiter.maybeExecute(data);
166 } else {
167 showRateLimitWarning();
168 }
169};
170
171// Access the selected state (will be empty object {} unless selector provided)
172const { executionCount, rejectionCount } = rateLimiter.state;
173```