Skip to main content

Overview

The useRateLimit 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 using hookAPI() to expose your rate limits:

Server API Options

The hookAPI method accepts two parameters:
  1. name (string): The rate limit name from your RateLimiter definition
  2. options (optional):
    • key: String or async function to determine the rate limit key
    • sampleShards: 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

The hookAPI returns a getServerTime mutation that helps synchronize client and server clocks:
From the source code (client/index.ts:264-270):
This ensures accurate retryAt calculations even when client and server clocks differ.

Using the Hook in React

Basic Usage

Hook Options

The useRateLimit hook accepts these options:

Return Value

The hook returns:

The check() Function

Use check() to get detailed rate limit information at specific times:
From the source (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):
The component automatically re-renders when 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

  1. Always use getServerTimeMutation: Ensures accurate retry times even with clock skew
  2. Handle loading state: The hook returns undefined while loading
  3. Show countdown timers: Give users feedback on when they can retry
  4. Check before actions: Use the hook to enable/disable UI elements
  5. Combine with server checks: Client-side checks are advisory; always check server-side too
Client-side checks are not security: Always enforce rate limits on the server. The React hook is for UX only.

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.