Upstash Documentation

Client-Side Usage

2 min read

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#

apiobject#

API configuration: - url: The realtime endpoint URL - withCredentials: Whether to send cookies with requests

Default: "{ url: \"/api/realtime\", withCredentials: false }"

maxReconnectAttemptsnumber#

Maximum number of reconnection attempts before giving up

Default: "3"

providers.tsx

Hook Options#

eventsstring[]#

Array of event names to subscribe to (e.g. ["notification.alert", "chat.message"])

onDatafunction#

Callback when an event is received. Receives an object with event, data, and channel.

channelsstring[]#

Array of channel names to subscribe to

Default: "[\"default\"]"

enabledboolean#

Whether the subscription is active. Set to false to disconnect.

Default: "true"

Return Value#

The hook returns an object with:

statusConnectionStatus#

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

Show real-time notifications to users:

notifications.tsx
Realtime Chat

Build a real-time chat:

chat.tsx
Live Dashboard

Update metrics in real-time:

dashboard.tsx
Collaborative Editing

Sync changes across users:

editor.tsx

Next Steps#