Overview
TheuseRateLimit hook allows you to check rate limit status directly in your React components. This enables you to:
- Show real-time rate limit status to users
- Disable buttons when rate limited
- Display countdown timers until retry is available
- Provide better UX by checking limits client-side before sending requests
Setting Up the Server API
First, create server queries usinghookAPI() to expose your rate limits:
Server API Options
ThehookAPI method accepts two parameters:
- name (string): The rate limit name from your RateLimiter definition
- options (optional):
key: String or async function to determine the rate limit keysampleShards: Number of shards to sample (if using sharding)
Key Function Patterns
1. Server-Determined Key
2. Client-Provided Key with Validation
3. Static Key
The getServerTime Mutation
ThehookAPI returns a getServerTime mutation that helps synchronize client and server clocks:
client/index.ts:264-270):
retryAt calculations even when client and server clocks differ.
Using the Hook in React
Basic Usage
Hook Options
TheuseRateLimit hook accepts these options:
Return Value
The hook returns:The check() Function
Usecheck() to get detailed rate limit information at specific times:
react/index.ts:81-103):
Complete Example: Message Sender
Auto-Refreshing Status
The hook automatically refreshes when the rate limit recovers: From the source (react/index.ts:119-123):
retryAt is reached.
Countdown Timer Example
Multiple Token Check
Check if enough tokens are available for different actions:Client-Provided Keys
When the server allows client-provided keys:Best Practices
- Always use getServerTimeMutation: Ensures accurate retry times even with clock skew
- Handle loading state: The hook returns
undefinedwhile loading - Show countdown timers: Give users feedback on when they can retry
- Check before actions: Use the hook to enable/disable UI elements
- Combine with server checks: Client-side checks are advisory; always check server-side too
Type Safety
The hook is fully typed with TypeScript:For more on rate limiting patterns, see Dynamic Limits for runtime configuration and Jitter for handling burst traffic.