useRealtime hook connects your React components to realtime events with full type safety.
Setup
1. Add the Provider
Wrap your app in theRealtimeProvider:
providers.tsx
layout.tsx
2. Create Typed Hook
Create a typeduseRealtime hook using createRealtime:
lib/realtime-client.ts
Basic Usage
Subscribe to events in any client component:page.tsx
Provider Options
object
API configuration: -
url: The realtime endpoint URL - withCredentials: Whether to
send cookies with requestsnumber
default:"3"
Maximum number of reconnection attempts before giving up
providers.tsx
Hook Options
string[]
Array of event names to subscribe to (e.g.
["notification.alert", "chat.message"])function
Callback when an event is received. Receives an object with
event, data, and
channel.string[]
default:"[\"default\"]"
Array of channel names to subscribe to
boolean
default:"true"
Whether the subscription is active. Set to
false to disconnect.Return Value
The hook returns an object with: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
Live Notifications
Live Notifications
Show real-time notifications to users:
notifications.tsx
Realtime Chat
Realtime Chat
Build a real-time chat:
chat.tsx
Live Dashboard
Live Dashboard
Update metrics in real-time:
dashboard.tsx
Collaborative Editing
Collaborative Editing
Sync changes across users:
editor.tsx
Next Steps
Channels
Scope events to specific rooms or users
History
Configure message retention and replay