use-signalr
Concepts

Lazy hubs

Connect a hub only while a consumer needs it, and keep it open for a grace period.

By default, the library connects every hub in the contract when the app starts. A lazy hub connects only when a consumer needs it. Set lazy: true for one hub, or for all hubs.

Grace period

graceMs is the time that a lazy hub stays connected after its last consumer leaves. A short grace period prevents a disconnect and a new connect when a component remounts quickly. The default is 0. graceMs is a per-hub option.

When the grace period ends, the hub stops and its status is "idle". When a consumer comes back, the hub connects again.

What counts as a consumer

The library counts the consumers of each hub. The hub is wanted while the count is more than 0. A consumer is not a component. It is one call of a helper that is bound to a hub.

Each of these counts as a consumer for the hub that you pass:

  • injectKeepHubAlive, which keeps the hub connected and does nothing else.
  • injectHubEvent, injectHubInvoke, injectHubSend, and injectHubTeardown.
  • injectHubStatus and injectOnReconnected.

The consumer ends when the injection context is destroyed.

A status banner for a lazy hub also connects that hub. To read the status without a connection, use injectSignalR. Its getStatus function does not count as a consumer.

Here, a component keeps the lazy presence hub alive and shows its online count:

lazy.ts
import { Component, signal } from "@angular/core";
import { injectHubEvent } from "./client";

@Component({ selector: "app-online-count", template: `{{ count() }} online` })
export class OnlineCountComponent {
  count = signal(0);

  constructor() {
    // A subscription keeps the lazy hub connected until this component is destroyed.
    injectHubEvent("/hubs/presence", "OnlineCount", (count) => this.count.set(count));
  }
}

A teardown call holds a lazy hub open until it is sent, even after its own consumer leaves.

On this page