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:

  • useHubConsumer, which keeps the hub connected and does nothing else.
  • useSignalREvent, useSignalRInvoke, useSignalRSend, and useSignalRTeardown.
  • useHubStatus and useOnReconnected.

The consumer ends when the effect scope of the helper stops, for example when the component unmounts.

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

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

lazy.vue
<script setup lang="ts">
import { ref } from "vue";
import { useSignalREvent } from "./client";

const count = ref(0);

// The subscription keeps the lazy hub connected while this component lives.
useSignalREvent("/hubs/presence", "OnlineCount", (online) => {
  count.value = online;
});
</script>

<template>
  <p>{{ count }} online</p>
</template>

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

On this page