Skip to main content
The useRealtime hook connects your React components to realtime events with full type safety.

Setup

1. Add the Provider

Wrap your app in the RealtimeProvider:
providers.tsx
layout.tsx

2. Create Typed Hook

Create a typed useRealtime hook using createRealtime:
lib/realtime-client.ts

Basic Usage

Subscribe to events in any client component:
page.tsx

Provider Options

api
object
API configuration: - url: The realtime endpoint URL - withCredentials: Whether to send cookies with requests
maxReconnectAttempts
number
default:"3"
Maximum number of reconnection attempts before giving up
providers.tsx

Hook Options

events
string[]
Array of event names to subscribe to (e.g. ["notification.alert", "chat.message"])
onData
function
Callback when an event is received. Receives an object with event, data, and channel.
channels
string[]
default:"[\"default\"]"
Array of channel names to subscribe to
enabled
boolean
default:"true"
Whether the subscription is active. Set to false to disconnect.

Return Value

The hook returns an object with:
status
ConnectionStatus
Current connection state: "connecting", "connected", "disconnected", or "error"
page.tsx

Connection Control

Enable or disable connections dynamically:
page.tsx

Conditional Connections

Connect only when certain conditions are met:
page.tsx

Multiple Events

Subscribe to multiple events at once:
page.tsx

Multiple Channels

Subscribe to multiple channels at once:
page.tsx

Dynamic Channel Management

Add and remove channels dynamically:
page.tsx

Custom API Endpoint

Configure a custom realtime endpoint in the provider:
providers.tsx

Use Cases

Show real-time notifications to users:
notifications.tsx
Build a real-time chat:
chat.tsx
Update metrics in real-time:
dashboard.tsx
Sync changes across users:
editor.tsx

Next Steps

Channels

Scope events to specific rooms or users

History

Configure message retention and replay