use-signalr
Concepts

Connection status

The five statuses of a hub and the events that change them.

Each hub has its own status. The status is one of five values.

StatusMeaning
idleNo connection is wanted. This is the status before the session starts, during server rendering, and when enabled is false or baseUrl is empty. It is also the status after the session stops, and for a lazy hub with no consumer. It shows briefly during a rebuild.
connectingThe first attempt runs, or the library waits for its next rebuild. The status stays connecting through all retries.
connectedThe connection is up.
reconnectingSignalR auto-reconnect runs. This needs reconnect other than false.
disconnectedThe hub is wanted but stopped for good. The cause is a 400, 401, 403, or 404 response to the negotiate request, or a configuration error. The library does not retry.

A configuration error is a binary protocol with Server-Sent Events from a factory, or a configureBuilder or protocol factory that throws.

Read the status

useHubStatus returns the status of a hub. It updates when the status changes. This component shows a banner while the hub is not connected:

status.tsx
import type { HubConnectionStatus } from "@dammers/use-signalr-preact";
import { useHubStatus } from "./client";

const messages: Record<HubConnectionStatus, string | null> = {
  idle: null,
  connecting: "Connecting...",
  connected: null,
  reconnecting: "Connection lost. Reconnecting...",
  disconnected: "Disconnected. Sign in again to reconnect.",
};

export function StatusBanner() {
  const message = messages[useHubStatus("/hubs/rooms")];
  return message && <p role="status">{message}</p>;
}

The helper counts as a consumer, so it also starts a lazy hub. See Lazy hubs.

Transitions

EventStatusesReconnect callbacks
Startidle, connecting, connectedno
A connect attempt fails with a retriable errorstays connecting. The library retries after 2.5, 5, 7.5 s, and so on, up to 30 sno
The connection drops, auto-reconnect is onconnected, reconnecting, connectedyes
Auto-reconnect gives upreconnecting, connecting, a library rebuild, connectedyes
The connection drops with reconnect: falseconnected, connecting, connected after 2.5 syes
A non-retriable errorconnecting, disconnectedno
baseUrl, enabled, or connectionKey changesidle, connecting, connectedyes, if the hub was connected before
A lazy hub loses its last consumerconnected, idle after graceMsno
A lazy hub gets a consumer againidle, connecting, connectedno
The session stops and starts againidle, connecting, connectedno

During server rendering, the status is idle.

The first client render also shows idle, so hydration matches.

For the retries behind these transitions, see Recovery.

On this page