Skip to main content
Enable or disable connections dynamically:
page.tsx
"use client"

import { useState } from "react"
import { useRealtime } from "@upstash/realtime/client"
import type { RealtimeEvents } from "@/lib/realtime"

export default function Page() {
  const [enabled, setEnabled] = useState(true)

  const { status } = useRealtime<RealtimeEvents>({
    enabled,
    events: {
      notification: {
        alert: (data) => console.log(data),
      },
    },
  })

  return (
    <div>
      <button onClick={() => setEnabled((prev) => !prev)}>
        {enabled ? "Disconnect" : "Connect"}
      </button>
      <p>Status: {status}</p>
    </div>
  )
}

Connection States

The status value indicates the current connection state:
connecting
string
Initial connection is being established
connected
string
Active connection, receiving events
reconnecting
string
Reconnecting after timeout or network interruption
disconnected
string
Connection closed (either by setting enabled: false or error)

Best Practices

Establish a realtime connection only when needed:
page.tsx
"use client"

import { useRealtime } from "@upstash/realtime/client"

export default function Page({ userId }: { userId?: string }) {
  useRealtime<RealtimeEvents>({
    // 👇 only connect if userId exists
    enabled: Boolean(userId),
    channel: `user-${userId}`,
    events: {
      notification: {
        alert: (data) => console.log(data),
      },
    },
  })

  return <div>Notifications {userId ? "enabled" : "disabled"}</div>
}