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:
2. Create Typed Hook#
Create a typed useRealtime hook using createRealtime:
Basic Usage#
Subscribe to events in any client component:
Provider Options#
API configuration: - url: The realtime endpoint URL - withCredentials: Whether to
send cookies with requests
Default: "{ url: \"/api/realtime\", withCredentials: false }"
Hook Options#
Array of event names to subscribe to (e.g. ["notification.alert", "chat.message"])
Callback when an event is received. Receives an object with event, data, and
channel.
Return Value#
The hook returns an object with:
Current connection state: "connecting", "connected", "disconnected", or "error"
Connection Control#
Enable or disable connections dynamically:
Conditional Connections#
Connect only when certain conditions are met:
Multiple Events#
Subscribe to multiple events at once:
Multiple Channels#
Subscribe to multiple channels at once:
Dynamic Channel Management#
Add and remove channels dynamically:
Custom API Endpoint#
Configure a custom realtime endpoint in the provider:
Use Cases#
Live Notifications
Show real-time notifications to users:
Realtime Chat
Build a real-time chat:
Live Dashboard
Update metrics in real-time:
Collaborative Editing
Sync changes across users: