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.

A controller from session.hub(host, hub) is one consumer. It counts while its host is connected to the DOM. controller.on, controller.invoke, controller.send, controller.teardown, controller.status, and controller.onReconnected are methods of this controller. They use this one consumer.

A status banner for a lazy hub also connects that hub. To read the status without a connection, use session.context. 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 { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { session } from "./provider";

@customElement("online-count")
export class OnlineCount extends LitElement {
  private presence = session.hub(this, "/hubs/presence");
  @state() private count = 0;

  constructor() {
    super();
    this.presence.on("OnlineCount", (count) => {
      this.count = count;
    });
  }

  render() {
    return html`${this.count} online`;
  }
}

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

On this page