@dammers/use-signalr-react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DammersCode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,191 @@
1
+ # @dammers/use-signalr-react
2
+
3
+ A typed, reusable [SignalR](https://learn.microsoft.com/aspnet/core/signalr) provider and hook set for React, driven by your contract.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-react.svg)](https://www.npmjs.com/package/@dammers/use-signalr-react)
6
+ [![types](https://img.shields.io/badge/types-included-blue.svg)](#api)
7
+ [![license](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
8
+
9
+ ```ts
10
+ const { SignalRProvider, useSignalRInvoke } = createSignalRClient({
11
+ hubs: {
12
+ "/hubs/chat": {
13
+ methods: { SendMessage: method<[roomId: string, message: string]>() },
14
+ },
15
+ },
16
+ });
17
+ ```
18
+
19
+ One factory call returns a provider and a set of hooks, each typed against your hub contract. Event args, method args, and return values are all inferred from the config.
20
+
21
+ Shared concepts (the contract, per-hub config, invoke retry, send vs invoke vs teardown) are covered in the [root README](https://github.com/DammersCode/use-signalr#readme). This document covers React-specific install and usage.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ npm i @dammers/use-signalr-react @microsoft/signalr
27
+ ```
28
+
29
+ Requires React ≥ 19 and `@microsoft/signalr` ≥ 8 (tested against 8–10).
30
+
31
+ ## Usage
32
+
33
+ ### 1. Define your contract and create the client
34
+
35
+ The **keys of `config.hubs` declare the hubs**. Each hub's `events` (what the server pushes to you) and `methods` (what you invoke) are declared inline with the `event()` and `method()` markers.
36
+
37
+ ```ts
38
+ // signalr.ts
39
+ import { createSignalRClient, event, method } from "@dammers/use-signalr-react";
40
+
41
+ export const {
42
+ SignalRProvider,
43
+ useSignalR,
44
+ useSignalREffect,
45
+ useSignalRInvoke,
46
+ useSignalRSend,
47
+ useSignalRTeardown,
48
+ useHubStatus,
49
+ useOnReconnected,
50
+ useHubConsumer,
51
+ } = createSignalRClient({
52
+ hubs: {
53
+ "/hubs/chat": {
54
+ events: {
55
+ ReceiveMessage: event<[user: string, message: string]>(),
56
+ },
57
+ methods: {
58
+ SendMessage: method<[roomId: string, message: string]>(),
59
+ JoinRoom: method<[roomId: string], { success: boolean }>(),
60
+ },
61
+ // per-hub config also goes here (see the root README)
62
+ },
63
+ },
64
+ // global defaults (all optional):
65
+ // lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
66
+ });
67
+ ```
68
+
69
+ `event<Args>()` takes the handler's argument tuple. `method<Args, Return>()` takes the argument tuple and the resolved return type (default `void`).
70
+
71
+ ### 2. Mount the provider with your auth
72
+
73
+ ```tsx
74
+ import { SignalRProvider } from "./signalr";
75
+
76
+ <SignalRProvider
77
+ baseUrl={serverUrl} // e.g. "https://api.example.com"
78
+ accessTokenFactory={() => getAccessToken()} // sync or async; read on every (re)negotiate
79
+ enabled={isAuthenticated} // optional, default true; false -> stops + clears all connections
80
+ connectionKey={accessToken} // optional: forces reconnect when it changes (re-login)
81
+ onError={(hub, err) => toast.error(`Connection to ${hub} failed`)}
82
+ onStatusChange={(hub, status) => {
83
+ if (status === "reconnecting") toast.warning(`Reconnecting to ${hub}…`);
84
+ if (status === "reconnected") toast.success(`Reconnected to ${hub}`);
85
+ }}
86
+ >
87
+ <App />
88
+ </SignalRProvider>;
89
+ ```
90
+
91
+ ### 3. Use the hooks — everything below is fully typed
92
+
93
+ ```tsx
94
+ // Listen to a server event — args inferred from the contract
95
+ useSignalREffect("/hubs/chat", "ReceiveMessage", (user, message) => {
96
+ console.log(user, message);
97
+ });
98
+
99
+ // Invoke a server method — args + return inferred, waits for connection
100
+ const sendMessage = useSignalRInvoke("/hubs/chat", "SendMessage");
101
+ await sendMessage(roomId, "hello"); // typed params, Promise<void>
102
+
103
+ // Typed fire-and-forget — does not wait for connection; drops if not connected.
104
+ // Stable across renders — safe to capture in an unmount cleanup.
105
+ const send = useSignalRSend("/hubs/chat", "SendMessage");
106
+ await send(roomId, "bye"); // typed args; Promise<boolean> (true = dispatched)
107
+
108
+ // Reliable teardown — for a method called in an effect cleanup. Survives
109
+ // unmount, queues while the hub connects (instead of dropping), and holds a
110
+ // lazy hub open until it flushes. Best-effort: Promise<boolean> (true = dispatched).
111
+ const leaveRoom = useSignalRTeardown("/hubs/chat", "LeaveRoomAsync");
112
+ useEffect(() => {
113
+ joinRoom(roomId);
114
+ return () => {
115
+ leaveRoom(roomId);
116
+ }; // lands even mid-connect or after unmount
117
+ }, [roomId, joinRoom, leaveRoom]);
118
+
119
+ // Live connection status — re-renders only when this hub's status changes
120
+ const status = useHubStatus("/hubs/chat"); // "connecting" | "connected" | "reconnecting" | ...
121
+
122
+ // Re-sync after a reconnect, for example to refetch a query
123
+ useOnReconnected("/hubs/chat", () => refetchMessages());
124
+
125
+ // Keep a lazy hub connected for this component's lifetime without subscribing
126
+ useHubConsumer("/hubs/chat");
127
+
128
+ // Last resort: the raw HubConnection (prefer the typed hooks above)
129
+ const { getConnection } = useSignalR();
130
+ getConnection("/hubs/chat")?.send("SendMessage", roomId, "bye");
131
+ ```
132
+
133
+ ### Reliable join/leave (session pattern)
134
+
135
+ A common pattern joins a session on mount and leaves it in the effect cleanup.
136
+
137
+ ```tsx
138
+ const joinRoom = useSignalRInvoke("/hubs/chat", "JoinRoomAsync");
139
+ const leaveRoom = useSignalRTeardown("/hubs/chat", "LeaveRoomAsync");
140
+
141
+ useEffect(() => {
142
+ joinRoom(roomId);
143
+ return () => {
144
+ leaveRoom(roomId);
145
+ };
146
+ }, [roomId, joinRoom, leaveRoom]);
147
+ ```
148
+
149
+ A plain `useSignalRInvoke` or `useSignalRSend` makes the **leave** unreliable:
150
+
151
+ - `useSignalRInvoke` aborts in-flight calls on unmount, so a leave issued in cleanup can be cancelled before it reaches the server.
152
+ - `useSignalRSend` drops silently if the hub is not `Connected`, so a leave that races a still-connecting socket (StrictMode's first mount, a fast route switch) is lost.
153
+
154
+ `useSignalRTeardown` fixes both problems. It:
155
+
156
+ - **survives the calling component's unmount** — it runs detached and is never aborted,
157
+ - **queues while connecting** — it waits up to `timeout` (default 10s) for the hub, then sends, instead of dropping,
158
+ - **holds a lazy hub open** until the flush completes, even if the unmounting component was its last consumer.
159
+
160
+ It is best-effort and fire-and-forget: it resolves `true` once dispatched, `false` if the hub never connected in time, and never throws. It also lands correctly under StrictMode's mount→cleanup→mount, at the cost of one extra round-trip.
161
+
162
+ > If your leave already uses `useSignalRInvoke` and only needs to avoid the abort on unmount, pass `{ keepAliveOnUnmount: true }`. This covers the abort case but **not** the still-connecting race. For that race, use `useSignalRTeardown`.
163
+
164
+ ## API
165
+
166
+ | Export | What it does |
167
+ | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
168
+ | `createSignalRClient(config)` | Returns the provider and hooks, typed against the contract **inferred** from `config`. |
169
+ | `event<Args>()` | Declares a server-pushed event inside a hub's `events`. `Args` is the handler's argument tuple. |
170
+ | `method<Args, Return?>()` | Declares an invocable server method inside a hub's `methods`. `Args` is the argument tuple; `Return` is the resolved return type (default `void`). |
171
+ | `<SignalRProvider>` | Builds and starts connections, retries, and auto-reconnects. |
172
+ | `useSignalREffect(hub, event, handler)` | Subscribes to a server event for the component's lifetime. |
173
+ | `useSignalRInvoke(hub, method, opts?)` | Typed request/response invoker. Waits for the connection and returns the method's result. Optional retry/backoff/timeout; `keepAliveOnUnmount` skips the unmount abort. |
174
+ | `useSignalRSend(hub, method)` | Typed fire-and-forget sender. **Drops** if not connected. For high-frequency signals where loss is acceptable. Safe in unmount cleanups. |
175
+ | `useSignalRTeardown(hub, method, opts?)` | Reliable teardown sender for a method called in cleanup: survives unmount, **queues** while connecting instead of dropping, and holds a lazy hub open until flushed. |
176
+ | `useHubStatus(hub)` | Live connection status. Re-renders only when that hub changes. |
177
+ | `useOnReconnected(hub, cb)` | Runs `cb` after the hub reconnects, for example to refetch. |
178
+ | `useHubConsumer(hub)` | Keeps a lazy hub connected for the component's lifetime without subscribing. |
179
+ | `useSignalR()` | Last-resort raw context: `getConnection`, `isHubConnected`, `getStatus`. |
180
+
181
+ ### Provider props
182
+
183
+ Required: `baseUrl`, `accessTokenFactory`. Optional: `enabled` (default `true`), `connectionKey`, `onStatusChange`, `onError`. Connection behavior (`lazy`, `reconnect`, `maxConnectRetries`, `logLevel`, per-hub overrides) lives in the **config** passed to `createSignalRClient`, not on the provider.
184
+
185
+ ## More
186
+
187
+ Per-hub config, invoke retry semantics, the send/invoke/teardown comparison, and notes on token rotation live in the [root README](https://github.com/DammersCode/use-signalr#readme). Contributing setup lives in [CONTRIBUTING.md](https://github.com/DammersCode/use-signalr/blob/main/CONTRIBUTING.md).
188
+
189
+ ## License
190
+
191
+ MIT © [DammersCode](https://github.com/DammersCode)
@@ -0,0 +1,64 @@
1
+ import type { HubDef, HubString, InferContract, SignalRClientConfig } from "@dammers/use-signalr-core";
2
+ import type { SignalRContextValue } from "./types";
3
+ /**
4
+ * Creates a fully-typed SignalR client. Returns a provider and hooks, typed
5
+ * against the contract inferred from `config.hubs`: the keys declare the
6
+ * hubs, and each hub's `event()`/`method()` declarations declare its events
7
+ * and methods.
8
+ */
9
+ export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): {
10
+ /**
11
+ * Provider that builds, starts, retries, and auto-reconnects every
12
+ * configured hub. Pass `baseUrl` and `accessTokenFactory`, and gate them
13
+ * with `enabled`. Mount it once, near the root.
14
+ */
15
+ SignalRProvider: ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: import("./types").SignalRProviderProps) => import("react").JSX.Element;
16
+ /**
17
+ * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
18
+ * `isHubConnected`, and more). Prefer the typed hooks below. Use this only
19
+ * for the underlying `HubConnection` or a non-reactive point read.
20
+ */
21
+ useSignalR: () => SignalRContextValue<InferContract<H>>;
22
+ /**
23
+ * Keeps a (possibly lazy) hub connected for the component's lifetime,
24
+ * without subscribing to events or status. Acquires on mount, releases on
25
+ * unmount.
26
+ */
27
+ useHubConsumer: (hub: keyof H & `/${string}`) => void;
28
+ /**
29
+ * Subscribes to a typed server event for the component's lifetime.
30
+ * Handler args are inferred from your contract. Re-attaches across
31
+ * reconnects.
32
+ */
33
+ useSignalREffect: <H_1 extends keyof H & `/${string}`, E extends import("@dammers/use-signalr-core").EventName<InferContract<H>, H_1>>(hub: H_1, event: E, handler: (...args: import("@dammers/use-signalr-core").EventArgs<InferContract<H>, H_1, E>) => void) => void;
34
+ /**
35
+ * Typed invoker that waits for the connection and resolves with the
36
+ * method's return value. Fails fast by default. Opt in to retry for
37
+ * idempotent methods only.
38
+ */
39
+ useSignalRInvoke: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M, options?: import("@dammers/use-signalr-core").InvokeOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<import("@dammers/use-signalr-core").MethodReturn<InferContract<H>, H_1, M>>;
40
+ /**
41
+ * Typed fire-and-forget sender. Does not wait for the connection: it
42
+ * drops the call (resolves `false`) if not connected, otherwise it
43
+ * dispatches the call (`true`). Safe in unmount cleanups.
44
+ */
45
+ useSignalRSend: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<boolean>;
46
+ /**
47
+ * Typed RELIABLE teardown sender for a method invoked in an effect
48
+ * cleanup. Survives the calling component's unmount, queues while the hub
49
+ * is still connecting instead of dropping, and holds a lazy hub open
50
+ * until the flush completes. Best-effort: resolves `true` if dispatched,
51
+ * `false` if the hub never connected in time. Never throws.
52
+ */
53
+ useSignalRTeardown: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M, options?: import("@dammers/use-signalr-core").TeardownOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<boolean>;
54
+ /**
55
+ * Live connection status of a hub. Re-renders only when THIS hub's status
56
+ * changes. Also keeps a lazy hub connected while mounted.
57
+ */
58
+ useHubStatus: <H_1 extends keyof H & `/${string}`>(hub: H_1) => import("@dammers/use-signalr-core").HubConnectionStatus;
59
+ /**
60
+ * Runs a callback after each reconnect, not the first connect, to refetch
61
+ * state that went stale while offline.
62
+ */
63
+ useOnReconnected: <H_1 extends keyof H & `/${string}`>(hub: H_1, callback: () => void) => void;
64
+ };
@@ -0,0 +1,74 @@
1
+ import { createContext } from "react";
2
+ import { hubKeys, resolveHubConfig } from "@dammers/use-signalr-core";
3
+ import { createSignalRProvider } from "./internal/create-provider";
4
+ import { createSignalRHooks } from "./internal/create-hooks";
5
+ /**
6
+ * Creates a fully-typed SignalR client. Returns a provider and hooks, typed
7
+ * against the contract inferred from `config.hubs`: the keys declare the
8
+ * hubs, and each hub's `event()`/`method()` declarations declare its events
9
+ * and methods.
10
+ */
11
+ export function createSignalRClient(config) {
12
+ const hubs = hubKeys(config);
13
+ const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config, config.hubs[h])]));
14
+ const resolve = (hub) => resolved.get(hub);
15
+ const Context = createContext(null);
16
+ const SignalRProvider = createSignalRProvider(Context, hubs, resolve);
17
+ const hooks = createSignalRHooks(Context);
18
+ return {
19
+ /**
20
+ * Provider that builds, starts, retries, and auto-reconnects every
21
+ * configured hub. Pass `baseUrl` and `accessTokenFactory`, and gate them
22
+ * with `enabled`. Mount it once, near the root.
23
+ */
24
+ SignalRProvider,
25
+ /**
26
+ * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
27
+ * `isHubConnected`, and more). Prefer the typed hooks below. Use this only
28
+ * for the underlying `HubConnection` or a non-reactive point read.
29
+ */
30
+ useSignalR: hooks.useSignalR,
31
+ /**
32
+ * Keeps a (possibly lazy) hub connected for the component's lifetime,
33
+ * without subscribing to events or status. Acquires on mount, releases on
34
+ * unmount.
35
+ */
36
+ useHubConsumer: hooks.useHubConsumer,
37
+ /**
38
+ * Subscribes to a typed server event for the component's lifetime.
39
+ * Handler args are inferred from your contract. Re-attaches across
40
+ * reconnects.
41
+ */
42
+ useSignalREffect: hooks.useSignalREffect,
43
+ /**
44
+ * Typed invoker that waits for the connection and resolves with the
45
+ * method's return value. Fails fast by default. Opt in to retry for
46
+ * idempotent methods only.
47
+ */
48
+ useSignalRInvoke: hooks.useSignalRInvoke,
49
+ /**
50
+ * Typed fire-and-forget sender. Does not wait for the connection: it
51
+ * drops the call (resolves `false`) if not connected, otherwise it
52
+ * dispatches the call (`true`). Safe in unmount cleanups.
53
+ */
54
+ useSignalRSend: hooks.useSignalRSend,
55
+ /**
56
+ * Typed RELIABLE teardown sender for a method invoked in an effect
57
+ * cleanup. Survives the calling component's unmount, queues while the hub
58
+ * is still connecting instead of dropping, and holds a lazy hub open
59
+ * until the flush completes. Best-effort: resolves `true` if dispatched,
60
+ * `false` if the hub never connected in time. Never throws.
61
+ */
62
+ useSignalRTeardown: hooks.useSignalRTeardown,
63
+ /**
64
+ * Live connection status of a hub. Re-renders only when THIS hub's status
65
+ * changes. Also keeps a lazy hub connected while mounted.
66
+ */
67
+ useHubStatus: hooks.useHubStatus,
68
+ /**
69
+ * Runs a callback after each reconnect, not the first connect, to refetch
70
+ * state that went stale while offline.
71
+ */
72
+ useOnReconnected: hooks.useOnReconnected,
73
+ };
74
+ }
@@ -0,0 +1,5 @@
1
+ export { createSignalRClient } from "./create-signalr-client";
2
+ export { InvokeError, event, method } from "@dammers/use-signalr-core";
3
+ export type { StatusStore } from "./status-store";
4
+ export type { HubString, HubContract, SignalRContract, SignalRClientConfig, PerHubConfig, HubDef, EventDef, MethodDef, InferContract, ResolvedHubConfig, ReconnectConfig, InvokeOptions, TeardownOptions, HubConnectionStatus, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, } from "@dammers/use-signalr-core";
5
+ export type { SignalRProviderProps, SignalRContextValue } from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createSignalRClient } from "./create-signalr-client";
2
+ export { InvokeError, event, method } from "@dammers/use-signalr-core";
@@ -0,0 +1,14 @@
1
+ import type { Context } from "react";
2
+ import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "@dammers/use-signalr-core";
3
+ import type { SignalRContextValue } from "../types";
4
+ /** Builds the hooks bound to one client's context. */
5
+ export declare function createSignalRHooks<T extends SignalRContract>(ReactContext: Context<SignalRContextValue<T> | null>): {
6
+ useSignalR: () => SignalRContextValue<T>;
7
+ useHubConsumer: (hub: keyof T & `/${string}`) => void;
8
+ useHubStatus: <H extends keyof T & `/${string}`>(hub: H) => HubConnectionStatus;
9
+ useOnReconnected: <H extends keyof T & `/${string}`>(hub: H, callback: () => void) => void;
10
+ useSignalREffect: <H extends keyof T & `/${string}`, E extends EventName<T, H>>(hub: H, event: E, handler: (...args: EventArgs<T, H, E>) => void) => void;
11
+ useSignalRInvoke: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: InvokeOptions) => (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
12
+ useSignalRSend: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M) => (...args: MethodArgs<T, H, M>) => Promise<boolean>;
13
+ useSignalRTeardown: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: TeardownOptions) => (...args: MethodArgs<T, H, M>) => Promise<boolean>;
14
+ };
@@ -0,0 +1,194 @@
1
+ import { use, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
2
+ import { useLatest } from "../internal-hooks";
3
+ import { createInvoker, createSender, createTeardownSender } from "@dammers/use-signalr-core";
4
+ /** Builds the hooks bound to one client's context. */
5
+ export function createSignalRHooks(ReactContext) {
6
+ /**
7
+ * Escape hatch to the raw SignalR context. Prefer the typed hooks below.
8
+ * Reach for this only when you need the underlying `HubConnection` or a
9
+ * non-reactive point read.
10
+ *
11
+ * @returns The context value: `getConnection`, `isHubConnected`, `getStatus`,
12
+ * `waitForConnection`, `acquire`/`release`, `registerReconnect`, `statusStore`.
13
+ * @throws If called outside a `<SignalRProvider>`.
14
+ */
15
+ function useSignalR() {
16
+ const ctx = use(ReactContext);
17
+ if (!ctx)
18
+ throw new Error("useSignalR must be used within a SignalRProvider");
19
+ return ctx;
20
+ }
21
+ /**
22
+ * Keeps a (possibly lazy) hub alive for this component's lifetime, without
23
+ * subscribing to events or status. Acquires on mount, releases on unmount.
24
+ *
25
+ * Most hooks already do this internally. Use it directly only when you want
26
+ * a lazy hub connected for a component that does not otherwise touch it.
27
+ *
28
+ * @param hub The hub path to keep connected.
29
+ */
30
+ function useHubConsumer(hub) {
31
+ const { acquire, release } = useSignalR();
32
+ useEffect(() => {
33
+ acquire(hub);
34
+ return () => release(hub);
35
+ }, [hub, acquire, release]);
36
+ }
37
+ /**
38
+ * Live connection status of a hub. Re-renders the component only when THIS
39
+ * hub's status changes, not when another hub changes. Also keeps the hub
40
+ * alive while mounted, so a lazy hub connects on first use.
41
+ *
42
+ * @param hub The hub path to watch.
43
+ * @returns `"disconnected" | "connecting" | "connected" | "reconnecting" | "reconnected"`.
44
+ */
45
+ function useHubStatus(hub) {
46
+ const { statusStore } = useSignalR();
47
+ useHubConsumer(hub);
48
+ return useSyncExternalStore(statusStore.subscribe, () => statusStore.get(hub), () => statusStore.get(hub));
49
+ }
50
+ /**
51
+ * Runs a callback every time a hub reconnects, after a dropped connection
52
+ * is re-established, to refetch state that may have gone stale while
53
+ * offline. Does NOT fire on the first connect, only on reconnects.
54
+ *
55
+ * A fresh closure each render is fine — it does not re-subscribe or fire
56
+ * spuriously, so you do not need to memoize the callback.
57
+ *
58
+ * @param hub The hub path to watch.
59
+ * @param callback Invoked after each successful reconnect.
60
+ */
61
+ function useOnReconnected(hub, callback) {
62
+ const { registerReconnect } = useSignalR();
63
+ useHubConsumer(hub);
64
+ const cbRef = useLatest(callback);
65
+ useEffect(() => registerReconnect(hub, () => cbRef.current()), [hub, registerReconnect, cbRef]);
66
+ }
67
+ /**
68
+ * Subscribes to a typed server event for the lifetime of the component. The
69
+ * handler's args are inferred from your contract for `(hub, event)`. The
70
+ * subscription attaches once the hub is connected, re-attaches across
71
+ * reconnects, and detaches on unmount.
72
+ *
73
+ * A fresh closure each render is fine — it does not re-subscribe, so you do
74
+ * not need to memoize the handler.
75
+ *
76
+ * @param hub The hub path.
77
+ * @param event The event name, a key of that hub's `events`.
78
+ * @param handler Called with the event's typed args each time the server pushes it.
79
+ */
80
+ function useSignalREffect(hub, event, handler) {
81
+ const { getConnection } = useSignalR();
82
+ const status = useHubStatus(hub); // acquires lazy hub + re-renders on connect
83
+ const handlerRef = useLatest(handler);
84
+ useEffect(() => {
85
+ const connection = getConnection(hub);
86
+ if (!connection || status !== "connected")
87
+ return;
88
+ const listener = (...args) => handlerRef.current(...args);
89
+ connection.on(event, listener);
90
+ return () => connection.off(event, listener);
91
+ }, [hub, event, status, getConnection, handlerRef]);
92
+ }
93
+ /**
94
+ * Returns a stable, typed function that invokes a hub method and resolves
95
+ * with its return value. It waits, up to `timeout`, for the connection
96
+ * before it invokes, so calling right after mount is safe.
97
+ *
98
+ * Special behavior:
99
+ * - **Fails fast by default** (`retries: 0`): rethrows the raw server error,
100
+ * so callers see the original.
101
+ * - **Opt-in retry** for retriable failures (transport drops, timeouts),
102
+ * with jittered backoff. Business errors (a `HubException` thrown while
103
+ * still connected) are never retried.
104
+ * - **At-least-once when retrying.** Enable `retries` only for IDEMPOTENT methods.
105
+ * - **Auto-aborts** any in-flight call or retry loop on unmount, UNLESS
106
+ * `keepAliveOnUnmount: true`. For a method invoked in an effect cleanup,
107
+ * set that flag, or prefer {@link useSignalRTeardown}, which also handles
108
+ * the hub-still-connecting race.
109
+ *
110
+ * @param hub The hub path.
111
+ * @param method The method name, a key of that hub's `methods`.
112
+ * @param options Optional `retries`, `timeout`, `backoff`, `isRetriable`, `keepAliveOnUnmount`.
113
+ * @returns An async fn that takes the method's typed args and resolves to its typed return.
114
+ * @throws The raw error when `retries === 0`. Otherwise an {@link InvokeError}
115
+ * that wraps the last failure once attempts are exhausted.
116
+ */
117
+ function useSignalRInvoke(hub, method, options) {
118
+ const { waitForConnection, getConnection } = useSignalR();
119
+ useHubConsumer(hub);
120
+ const optsRef = useLatest(options);
121
+ const abortRef = useRef(null);
122
+ useEffect(() => () => {
123
+ if (!optsRef.current?.keepAliveOnUnmount)
124
+ abortRef.current?.abort();
125
+ }, [optsRef]);
126
+ return useMemo(() => createInvoker({ waitForConnection, getConnection }, hub, method, () => optsRef.current, (ac) => {
127
+ abortRef.current = ac;
128
+ }), [waitForConnection, getConnection, hub, method, optsRef]);
129
+ }
130
+ /**
131
+ * Returns a stable, typed fire-and-forget sender. Unlike {@link useSignalRInvoke},
132
+ * it does NOT wait for the connection and does NOT return the method's
133
+ * result. If the hub is not Connected, the call is dropped (resolves
134
+ * `false`); otherwise it is dispatched (resolves `true`).
135
+ *
136
+ * Reads the connection at call time and never depends on render-time state,
137
+ * so it is safe to capture in an unmount cleanup.
138
+ *
139
+ * @param hub The hub path.
140
+ * @param method The method name, a key of that hub's `methods`.
141
+ * @returns An async fn that takes the method's typed args and resolves
142
+ * `true` if dispatched, `false` if dropped because it was not connected.
143
+ */
144
+ function useSignalRSend(hub, method) {
145
+ const { getConnection } = useSignalR();
146
+ useHubConsumer(hub);
147
+ return useMemo(() => createSender(getConnection, hub, method), [getConnection, hub, method]);
148
+ }
149
+ /**
150
+ * Returns a stable, typed RELIABLE teardown sender, built for a method
151
+ * invoked in an effect cleanup. Unlike {@link useSignalRSend}, which drops
152
+ * a call if not yet connected, and {@link useSignalRInvoke}, which aborts
153
+ * in-flight calls on unmount, the returned function:
154
+ *
155
+ * - **Survives the calling component's unmount.** It runs detached, not
156
+ * tied to any effect or AbortController, so a call issued in cleanup
157
+ * still lands.
158
+ * - **Queues while connecting.** It waits, up to `timeout`, for the hub to
159
+ * (re)connect, then sends, instead of dropping the call.
160
+ * - **Holds a lazy hub open** until the flush completes, even when the
161
+ * calling component was the last consumer — it acquires and releases
162
+ * independently.
163
+ * - **Is best-effort and fire-and-forget.** It resolves `true` once
164
+ * dispatched, `false` if the hub never connected within `timeout`, and
165
+ * never throws.
166
+ *
167
+ * Trade-off: under StrictMode's mount→cleanup→mount, the intermediate
168
+ * teardown DOES fire, and the remount then re-runs setup. This is correct:
169
+ * the server is never left in a stale joined state, at the cost of one
170
+ * extra round-trip.
171
+ *
172
+ * @param hub The hub path.
173
+ * @param method The teardown method name, a key of that hub's `methods`.
174
+ * @param options Optional `timeout` in ms to wait for a connection. Default 10_000.
175
+ * @returns An async fn that takes the method's typed args and resolves
176
+ * `true` if dispatched, `false` if the hub never connected in time.
177
+ */
178
+ function useSignalRTeardown(hub, method, options) {
179
+ const { acquire, release, waitForConnection } = useSignalR();
180
+ useHubConsumer(hub);
181
+ const optsRef = useLatest(options);
182
+ return useMemo(() => createTeardownSender({ acquire, release, waitForConnection }, hub, method, () => optsRef.current), [acquire, release, waitForConnection, hub, method, optsRef]);
183
+ }
184
+ return {
185
+ useSignalR,
186
+ useHubConsumer,
187
+ useHubStatus,
188
+ useOnReconnected,
189
+ useSignalREffect,
190
+ useSignalRInvoke,
191
+ useSignalRSend,
192
+ useSignalRTeardown,
193
+ };
194
+ }
@@ -0,0 +1,5 @@
1
+ import type { Context } from "react";
2
+ import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
3
+ import type { SignalRContextValue, SignalRProviderProps } from "../types";
4
+ /** Builds the `SignalRProvider` component bound to one client's context. */
5
+ export declare function createSignalRProvider<T extends SignalRContract>(ReactContext: Context<SignalRContextValue<T> | null>, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: SignalRProviderProps) => import("react").JSX.Element;
@@ -0,0 +1,87 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useMemo, useRef } from "react";
3
+ import { useLatest } from "../internal-hooks";
4
+ import { createStatusStore } from "../status-store";
5
+ import { createConnectionManager } from "@dammers/use-signalr-core";
6
+ /** Builds the `SignalRProvider` component bound to one client's context. */
7
+ export function createSignalRProvider(ReactContext, hubs, resolve) {
8
+ return function SignalRProvider({ children, baseUrl, accessTokenFactory, enabled = true, connectionKey, onStatusChange, onError, }) {
9
+ const statusStore = useRef(createStatusStore()).current;
10
+ // Lazy ref-counts, pending stop timers, and reconnect listeners persist
11
+ // across rebuilds. The live manager is swapped per generation.
12
+ const refCounts = useRef(new Map()).current;
13
+ const stopTimers = useRef(new Map()).current;
14
+ const reconnectListeners = useRef(new Map()).current;
15
+ const managerRef = useRef(null);
16
+ // Latest props via refs, so once-attached handlers call the current props.
17
+ const tokenFactoryRef = useLatest(accessTokenFactory);
18
+ const onStatusChangeRef = useLatest(onStatusChange);
19
+ const onErrorRef = useLatest(onError);
20
+ useEffect(() => {
21
+ if (!enabled || !baseUrl) {
22
+ managerRef.current?.dispose();
23
+ managerRef.current = null;
24
+ hubs.forEach((h) => statusStore.set(h, "disconnected"));
25
+ return;
26
+ }
27
+ const manager = createConnectionManager({
28
+ baseUrl,
29
+ hubs,
30
+ resolve,
31
+ getAccessToken: () => tokenFactoryRef.current(),
32
+ refCounts,
33
+ stopTimers,
34
+ reconnectListeners,
35
+ onStatus: (hub, status) => {
36
+ statusStore.set(hub, status);
37
+ onStatusChangeRef.current?.(hub, status);
38
+ },
39
+ onError: (hub, err) => onErrorRef.current?.(hub, err),
40
+ isCurrent: () => managerRef.current === manager,
41
+ });
42
+ managerRef.current = manager;
43
+ manager.reconcile(); // build eager hubs plus already-referenced lazy hubs
44
+ return () => {
45
+ manager.dispose();
46
+ if (managerRef.current === manager)
47
+ managerRef.current = null;
48
+ };
49
+ // Rebuild only when the connection identity changes. tokenFactoryRef and
50
+ // on*Ref are stable; props are read through .current.
51
+ // eslint-disable-next-line react-hooks/exhaustive-deps
52
+ }, [baseUrl, enabled, connectionKey]);
53
+ const value = useMemo(() => ({
54
+ getConnection: (hub) => managerRef.current?.getConnection(hub) ?? null,
55
+ isHubConnected: (hub) => statusStore.get(hub) === "connected",
56
+ getStatus: (hub) => statusStore.get(hub),
57
+ statusStore,
58
+ waitForConnection: (hub, timeoutMs) => {
59
+ const manager = managerRef.current;
60
+ if (!manager) {
61
+ return Promise.reject(new Error(`SignalR not connected: ${String(hub)}`));
62
+ }
63
+ return manager.waitForConnection(hub, timeoutMs);
64
+ },
65
+ acquire: (hub) => {
66
+ const next = (refCounts.get(hub) ?? 0) + 1;
67
+ refCounts.set(hub, next);
68
+ if (next === 1)
69
+ managerRef.current?.reconcile();
70
+ },
71
+ release: (hub) => {
72
+ const next = Math.max(0, (refCounts.get(hub) ?? 0) - 1);
73
+ refCounts.set(hub, next);
74
+ if (next === 0)
75
+ managerRef.current?.reconcile();
76
+ },
77
+ registerReconnect: (hub, cb) => {
78
+ let set = reconnectListeners.get(hub);
79
+ if (!set)
80
+ reconnectListeners.set(hub, (set = new Set()));
81
+ set.add(cb);
82
+ return () => set.delete(cb);
83
+ },
84
+ }), [statusStore, refCounts, reconnectListeners]);
85
+ return _jsx(ReactContext, { value: value, children: children });
86
+ };
87
+ }
@@ -0,0 +1,2 @@
1
+ /** Ref that always holds the latest value, synced just before paint. */
2
+ export declare function useLatest<T>(value: T): import("react").RefObject<T>;
@@ -0,0 +1,10 @@
1
+ import { useEffect, useLayoutEffect, useRef } from "react";
2
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
3
+ /** Ref that always holds the latest value, synced just before paint. */
4
+ export function useLatest(value) {
5
+ const ref = useRef(value);
6
+ useIsomorphicLayoutEffect(() => {
7
+ ref.current = value;
8
+ });
9
+ return ref;
10
+ }
@@ -0,0 +1,11 @@
1
+ import type { StatusStore as StatusStoreBase } from "@dammers/use-signalr-core";
2
+ /**
3
+ * Small external store for hub statuses, consumed with `useSyncExternalStore`.
4
+ * Exposes only `subscribe`, `get`, and `set` — no whole-record snapshot — so
5
+ * a per-hub selector lets React skip a re-render when an unrelated hub's
6
+ * status changes.
7
+ */
8
+ export interface StatusStore<H extends string> extends StatusStoreBase<H> {
9
+ subscribe: (listener: () => void) => () => void;
10
+ }
11
+ export declare function createStatusStore<H extends string>(): StatusStore<H>;
@@ -0,0 +1,17 @@
1
+ export function createStatusStore() {
2
+ const snapshot = new Map();
3
+ const listeners = new Set();
4
+ return {
5
+ subscribe: (listener) => {
6
+ listeners.add(listener);
7
+ return () => listeners.delete(listener);
8
+ },
9
+ get: (hub) => snapshot.get(hub) ?? "disconnected",
10
+ set: (hub, status) => {
11
+ if (snapshot.get(hub) === status)
12
+ return; // dedupe: skip a spurious notify
13
+ snapshot.set(hub, status);
14
+ listeners.forEach((l) => l());
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,5 @@
1
+ import type { ReactNode } from "react";
2
+ import type { HubString, SignalRContract, SignalRProviderPropsBase, SignalRContextValueBase } from "@dammers/use-signalr-core";
3
+ import type { StatusStore } from "./status-store";
4
+ export type SignalRProviderProps = SignalRProviderPropsBase<ReactNode>;
5
+ export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@dammers/use-signalr-react",
3
+ "version": "0.1.0",
4
+ "description": "Fully-typed multi-hub SignalR provider + hooks for React: auto-reconnect, invoke retry, lazy hubs, live status.",
5
+ "author": "Dammers",
6
+ "license": "MIT",
7
+ "repository": "github:DammersCode/use-signalr",
8
+ "homepage": "https://github.com/DammersCode/use-signalr#readme",
9
+ "bugs": "https://github.com/DammersCode/use-signalr/issues",
10
+ "type": "module",
11
+ "sideEffects": false,
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.build.json",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "vitest run"
30
+ },
31
+ "dependencies": {
32
+ "@dammers/use-signalr-core": "0.1.0"
33
+ },
34
+ "peerDependencies": {
35
+ "@microsoft/signalr": ">=8",
36
+ "react": ">=19",
37
+ "react-dom": ">=19"
38
+ },
39
+ "devDependencies": {
40
+ "@microsoft/signalr": ">=8",
41
+ "@testing-library/react": "^16.1.0",
42
+ "@types/react": ">=19",
43
+ "react": ">=19",
44
+ "react-dom": ">=19"
45
+ }
46
+ }