@dammers/use-signalr-react 0.5.0 → 1.0.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/README.md CHANGED
@@ -1,222 +1,61 @@
1
1
  # @dammers/use-signalr-react
2
2
 
3
- A typed, reusable [SignalR](https://learn.microsoft.com/aspnet/core/signalr) provider and hook set for React, driven by your contract.
3
+ Provider and hooks for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr) in React. Part of [use-signalr](https://use-signalr.vercel.app).
4
4
 
5
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.
6
+ [![license](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/DammersCode/use-signalr/blob/main/LICENSE)
22
7
 
23
8
  ## Install
24
9
 
25
10
  ```bash
26
- npm i @dammers/use-signalr-react @microsoft/signalr
11
+ npm install @dammers/use-signalr-react @microsoft/signalr
27
12
  ```
28
13
 
29
- Requires React ≥ 19 and `@microsoft/signalr` ≥ 8 (tested against 8–10).
30
-
31
- ## Usage
14
+ It needs React ^19, `@microsoft/signalr` ^8 || ^9 || ^10, and Node 20.19 or later.
32
15
 
33
- ### 1. Define your contract and create the client
16
+ ## Example
34
17
 
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.
18
+ This file declares a hub, connects it, and reads a typed method result:
36
19
 
37
- ```ts
38
- // signalr.ts
39
- import { createSignalRClient, event, method } from "@dammers/use-signalr-react";
20
+ <!-- hero:react:start -->
21
+ ```tsx
22
+ import { useState } from "react";
23
+ import { createSignalRClient, method } from "@dammers/use-signalr-react";
40
24
 
41
- export const {
42
- SignalRProvider,
43
- useSignalR,
44
- useSignalREffect,
45
- useSignalRInvoke,
46
- useSignalRSend,
47
- useSignalRTeardown,
48
- useHubStatus,
49
- useOnReconnected,
50
- useHubConsumer,
51
- } = createSignalRClient({
25
+ const { SignalRProvider, useSignalRInvoke } = createSignalRClient({
52
26
  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)
27
+ "/hubs/rooms": {
28
+ methods: { GetHistory: method<[roomId: string], { text: string }[]>() },
62
29
  },
63
30
  },
64
- // global defaults (all optional):
65
- // lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
66
31
  });
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
32
 
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>;
33
+ function HistoryCount({ roomId }: { roomId: string }) {
34
+ const getHistory = useSignalRInvoke("/hubs/rooms", "GetHistory");
35
+ const [count, setCount] = useState(0);
36
+ const load = () => getHistory(roomId).then((m) => setCount(m.length)).catch(console.error);
37
+ return <button onClick={load}>{count} messages</button>;
38
+ }
39
+
40
+ export function App() {
41
+ return (
42
+ <SignalRProvider baseUrl="https://api.example.com" accessTokenFactory={() => "token"}>
43
+ <HistoryCount roomId="general" />
44
+ </SignalRProvider>
45
+ );
46
+ }
89
47
  ```
48
+ <!-- hero:react:end -->
90
49
 
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
- ## SSR (Next.js)
165
-
166
- The import is server-safe. No connection work happens at module scope or during a server render.
167
-
168
- `SignalRProvider` starts connections inside `useEffect`, which runs only in the browser. Every hub reports `"disconnected"` until that effect runs.
169
-
170
- Mark the component that mounts the provider with `"use client"`.
171
-
172
- ## Lazy hubs and `graceMs`
173
-
174
- Set `lazy: true` on a hub to connect it only when the first hook for that hub mounts. Consumers are ref-counted.
175
-
176
- After the last consumer unmounts, the connection stays open for `graceMs` milliseconds. If a new consumer mounts inside that window, the connection stays. The default is `0`.
177
-
178
- ```ts
179
- createSignalRClient({
180
- hubs: {
181
- "/hubs/presence": { lazy: true, graceMs: 5000 },
182
- },
183
- });
184
- ```
185
-
186
- ## `InvokeError`
187
-
188
- `useSignalRInvoke` throws `InvokeError` when its retry budget is exhausted. The error carries `cause` (the last underlying error), `attempts` (the total number of attempts), and `retriable` (whether the final failure was classed as retriable).
189
-
190
- `InvokeError` is thrown only when you set `retries` above `0`. With the default `retries: 0`, the raw server error propagates unchanged.
191
-
192
- The `timeout` option bounds only the wait for a connected hub before dispatch. SignalR cannot cancel an invocation after dispatch.
193
-
194
- ## API
195
-
196
- | Export | What it does |
197
- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
198
- | `createSignalRClient(config)` | Returns the provider and hooks, typed against the contract **inferred** from `config`. |
199
- | `event<Args>()` | Declares a server-pushed event inside a hub's `events`. `Args` is the handler's argument tuple. |
200
- | `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`). |
201
- | `<SignalRProvider>` | Builds and starts connections, retries, and auto-reconnects. |
202
- | `useSignalREffect(hub, event, handler)` | Subscribes to a server event for the component's lifetime. |
203
- | `useSignalRInvoke(hub, method, opts?)` | Typed request/response invoker. Returns the method's result. `timeout` bounds only the wait for a connected hub. `keepAliveOnUnmount` skips the unmount abort. |
204
- | `useSignalRSend(hub, method)` | Typed fire-and-forget sender. **Drops** if not connected. For high-frequency signals where loss is acceptable. Safe in unmount cleanups. |
205
- | `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. |
206
- | `useHubStatus(hub)` | Live connection status. Re-renders only when that hub changes. |
207
- | `useOnReconnected(hub, cb)` | Runs `cb` after the hub reconnects, for example to refetch. |
208
- | `useHubConsumer(hub)` | Keeps a lazy hub connected for the component's lifetime without subscribing. |
209
- | `useSignalR()` | Last-resort raw context: `getConnection`, `isHubConnected`, `getStatus`. |
210
- | `InvokeError` | Thrown by `useSignalRInvoke` once retries are exhausted. Wraps the last failure. |
211
-
212
- ### Provider props
213
-
214
- 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.
215
-
216
- ## More
50
+ ## Documentation
217
51
 
218
- 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).
52
+ - [Quick start](https://use-signalr.vercel.app/docs/react/quick-start)
53
+ - [Provider setup](https://use-signalr.vercel.app/docs/react/concepts/provider)
54
+ - [Events](https://use-signalr.vercel.app/docs/react/concepts/events) and [calls](https://use-signalr.vercel.app/docs/react/concepts/calls)
55
+ - [Connection status](https://use-signalr.vercel.app/docs/react/concepts/connection-status) and [recovery](https://use-signalr.vercel.app/docs/react/concepts/recovery)
56
+ - [API reference](https://use-signalr.vercel.app/docs/react/reference/api)
57
+ - [Troubleshooting](https://use-signalr.vercel.app/docs/react/reference/troubleshooting)
219
58
 
220
59
  ## License
221
60
 
222
- MIT © [DammersCode](https://github.com/DammersCode)
61
+ [MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
@@ -1,5 +1,4 @@
1
1
  import type { HubDef, HubString, InferContract, SignalRClientConfig } from "@dammers/use-signalr-core";
2
- import type { SignalRContextValue } from "./types.js";
3
2
  /**
4
3
  * Creates a fully-typed SignalR client. Returns a provider and hooks, typed
5
4
  * against the contract inferred from `config.hubs`: the keys declare the
@@ -12,13 +11,13 @@ export declare function createSignalRClient<const H extends Record<HubString, Hu
12
11
  * configured hub. Pass `baseUrl` and `accessTokenFactory`, and gate them
13
12
  * with `enabled`. Mount it once, near the root.
14
13
  */
15
- SignalRProvider: ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: import("./types.js").SignalRProviderProps) => import("react").JSX.Element;
14
+ SignalRProvider: ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: import("./types.js").SignalRProviderProps<keyof H & `/${string}`>) => import("react").JSX.Element;
16
15
  /**
17
- * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
18
- * `isHubConnected`, and more). Prefer the typed hooks below. Use this only
16
+ * Escape hatch to the SignalR context (`getConnection`, `getStatus`,
17
+ * and `waitForConnection`). Prefer the typed hooks below. Use this only
19
18
  * for the underlying `HubConnection` or a non-reactive point read.
20
19
  */
21
- useSignalR: () => SignalRContextValue<InferContract<H>>;
20
+ useSignalR: () => import("@dammers/use-signalr-core").SignalRPublicContext<InferContract<H>>;
22
21
  /**
23
22
  * Keeps a (possibly lazy) hub connected for the component's lifetime,
24
23
  * without subscribing to events or status. Acquires on mount, releases on
@@ -27,38 +26,43 @@ export declare function createSignalRClient<const H extends Record<HubString, Hu
27
26
  useHubConsumer: (hub: keyof H & `/${string}`) => void;
28
27
  /**
29
28
  * Subscribes to a typed server event for the component's lifetime.
30
- * Handler args are inferred from your contract. Re-attaches across
31
- * reconnects.
29
+ * Handler args are inferred from your contract. The subscription survives
30
+ * reconnects and rebuilds.
32
31
  */
33
32
  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
33
  /**
35
34
  * Typed invoker that waits for the connection and resolves with the
36
35
  * method's return value. Fails fast by default. Opt in to retry for
37
- * idempotent methods only.
36
+ * idempotent methods only. When the component unmounts, a call that still
37
+ * waits rejects with `AbortError`, unless you set `keepAliveOnUnmount`.
38
38
  */
39
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
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.
41
+ * Typed fire-and-forget sender. It does not wait for the connection. It
42
+ * resolves `true` when it sends the call, and `false` when the hub is not
43
+ * connected and it drops the call. It never throws, so a cleanup can call
44
+ * it. For a call that must land in a cleanup, use `useSignalRTeardown`.
44
45
  */
45
46
  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
  /**
47
- * Typed RELIABLE teardown sender for a method invoked in an effect
48
+ * Typed teardown sender for a method invoked in an effect
48
49
  * cleanup. Survives the calling component's unmount, queues while the hub
49
50
  * 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.
51
+ * until the flush completes. Resolves `true` if the call is sent.
52
+ * Resolves `false` if the hub does not connect in time,
53
+ * the session is disabled, the hub failed, or the send fails. Never
54
+ * throws.
52
55
  */
53
56
  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
57
  /**
55
- * Live connection status of a hub. Re-renders only when THIS hub's status
58
+ * Live connection status of a hub. Re-renders only when this hub's status
56
59
  * changes. Also keeps a lazy hub connected while mounted.
57
60
  */
58
61
  useHubStatus: <H_1 extends keyof H & `/${string}`>(hub: H_1) => import("@dammers/use-signalr-core").HubConnectionStatus;
59
62
  /**
60
63
  * Runs a callback after each reconnect, not the first connect, to refetch
61
- * state that went stale while offline.
64
+ * state that went stale while offline. It also runs after a rebuild that a
65
+ * `connectionKey`, `baseUrl`, or `enabled` change causes.
62
66
  */
63
67
  useOnReconnected: <H_1 extends keyof H & `/${string}`>(hub: H_1, callback: () => void) => void;
64
68
  };
@@ -10,7 +10,7 @@ import { createSignalRHooks } from "./internal/create-hooks.js";
10
10
  */
11
11
  export function createSignalRClient(config) {
12
12
  const hubs = hubKeys(config);
13
- const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config, config.hubs[h])]));
13
+ const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config, h)]));
14
14
  const resolve = (hub) => resolved.get(hub);
15
15
  const Context = createContext(null);
16
16
  const SignalRProvider = createSignalRProvider(Context, hubs, resolve);
@@ -23,8 +23,8 @@ export function createSignalRClient(config) {
23
23
  */
24
24
  SignalRProvider,
25
25
  /**
26
- * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
27
- * `isHubConnected`, and more). Prefer the typed hooks below. Use this only
26
+ * Escape hatch to the SignalR context (`getConnection`, `getStatus`,
27
+ * and `waitForConnection`). Prefer the typed hooks below. Use this only
28
28
  * for the underlying `HubConnection` or a non-reactive point read.
29
29
  */
30
30
  useSignalR: hooks.useSignalR,
@@ -36,38 +36,43 @@ export function createSignalRClient(config) {
36
36
  useHubConsumer: hooks.useHubConsumer,
37
37
  /**
38
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.
39
+ * Handler args are inferred from your contract. The subscription survives
40
+ * reconnects and rebuilds.
41
41
  */
42
42
  useSignalREffect: hooks.useSignalREffect,
43
43
  /**
44
44
  * Typed invoker that waits for the connection and resolves with the
45
45
  * method's return value. Fails fast by default. Opt in to retry for
46
- * idempotent methods only.
46
+ * idempotent methods only. When the component unmounts, a call that still
47
+ * waits rejects with `AbortError`, unless you set `keepAliveOnUnmount`.
47
48
  */
48
49
  useSignalRInvoke: hooks.useSignalRInvoke,
49
50
  /**
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.
51
+ * Typed fire-and-forget sender. It does not wait for the connection. It
52
+ * resolves `true` when it sends the call, and `false` when the hub is not
53
+ * connected and it drops the call. It never throws, so a cleanup can call
54
+ * it. For a call that must land in a cleanup, use `useSignalRTeardown`.
53
55
  */
54
56
  useSignalRSend: hooks.useSignalRSend,
55
57
  /**
56
- * Typed RELIABLE teardown sender for a method invoked in an effect
58
+ * Typed teardown sender for a method invoked in an effect
57
59
  * cleanup. Survives the calling component's unmount, queues while the hub
58
60
  * 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
+ * until the flush completes. Resolves `true` if the call is sent.
62
+ * Resolves `false` if the hub does not connect in time,
63
+ * the session is disabled, the hub failed, or the send fails. Never
64
+ * throws.
61
65
  */
62
66
  useSignalRTeardown: hooks.useSignalRTeardown,
63
67
  /**
64
- * Live connection status of a hub. Re-renders only when THIS hub's status
68
+ * Live connection status of a hub. Re-renders only when this hub's status
65
69
  * changes. Also keeps a lazy hub connected while mounted.
66
70
  */
67
71
  useHubStatus: hooks.useHubStatus,
68
72
  /**
69
73
  * Runs a callback after each reconnect, not the first connect, to refetch
70
- * state that went stale while offline.
74
+ * state that went stale while offline. It also runs after a rebuild that a
75
+ * `connectionKey`, `baseUrl`, or `enabled` change causes.
71
76
  */
72
77
  useOnReconnected: hooks.useOnReconnected,
73
78
  };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  export { createSignalRClient } from "./create-signalr-client.js";
2
- export { InvokeError, event, method } from "@dammers/use-signalr-core";
3
- export type { StatusStore } from "./status-store.js";
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.js";
2
+ export { event, method } from "@dammers/use-signalr-core";
3
+ export type { HubString, HubContract, SignalRContract, SignalRClientConfig, PerHubConfig, HubProtocolConfig, ConfigureBuilder, BuilderContext, HttpOptions, HubDef, EventDef, MethodDef, InferContract, ReconnectConfig, InvokeOptions, TeardownOptions, HubConnectionStatus, SignalRErrorInfo, SignalRPublicContext, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, } from "@dammers/use-signalr-core";
4
+ export type { SignalRProviderProps } from "./types.js";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  export { createSignalRClient } from "./create-signalr-client.js";
2
- export { InvokeError, event, method } from "@dammers/use-signalr-core";
2
+ export { event, method } from "@dammers/use-signalr-core";
@@ -1,14 +1,14 @@
1
1
  import type { Context } from "react";
2
- import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "@dammers/use-signalr-core";
2
+ import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodName, SignalRContract, SignalRPublicContext } from "@dammers/use-signalr-core";
3
3
  import type { SignalRContextValue } from "../types.js";
4
4
  /** Builds the hooks bound to one client's context. */
5
5
  export declare function createSignalRHooks<T extends SignalRContract>(ReactContext: Context<SignalRContextValue<T> | null>): {
6
- useSignalR: () => SignalRContextValue<T>;
6
+ useSignalR: () => SignalRPublicContext<T>;
7
7
  useHubConsumer: (hub: keyof T & `/${string}`) => void;
8
8
  useHubStatus: <H extends keyof T & `/${string}`>(hub: H) => HubConnectionStatus;
9
9
  useOnReconnected: <H extends keyof T & `/${string}`>(hub: H, callback: () => void) => void;
10
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>;
11
+ useSignalRInvoke: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: InvokeOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<import("@dammers/use-signalr-core").MethodReturn<T, H, M>>;
12
+ useSignalRSend: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M) => (...args: import("@dammers/use-signalr-core").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: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
14
14
  };
@@ -1,122 +1,45 @@
1
1
  import { use, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
2
2
  import { useLatest } from "../internal-hooks.js";
3
3
  import { createAbortScope, createInvoker, createSender, createTeardownSender, } from "@dammers/use-signalr-core";
4
+ const INITIAL_STATUS = "idle";
4
5
  /** Builds the hooks bound to one client's context. */
5
6
  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() {
7
+ function useInternalContext() {
16
8
  const ctx = use(ReactContext);
17
9
  if (!ctx)
18
10
  throw new Error("useSignalR must be used within a SignalRProvider");
19
11
  return ctx;
20
12
  }
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
- */
13
+ function useSignalR() {
14
+ return useInternalContext().publicContext;
15
+ }
30
16
  function useHubConsumer(hub) {
31
- const { acquire, release } = useSignalR();
17
+ const { acquire, release } = useInternalContext();
32
18
  useEffect(() => {
33
19
  acquire(hub);
34
20
  return () => release(hub);
35
21
  }, [hub, acquire, release]);
36
22
  }
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
23
  function useHubStatus(hub) {
46
- const { statusStore } = useSignalR();
24
+ const { statusStore } = useInternalContext();
47
25
  useHubConsumer(hub);
48
26
  const subscribe = useMemo(() => (listener) => statusStore.subscribe(hub, listener), [statusStore, hub]);
49
- return useSyncExternalStore(subscribe, () => statusStore.get(hub), () => statusStore.get(hub));
27
+ return useSyncExternalStore(subscribe, () => statusStore.get(hub), () => INITIAL_STATUS);
50
28
  }
51
- /**
52
- * Runs a callback every time a hub reconnects, after a dropped connection
53
- * is re-established, to refetch state that may have gone stale while
54
- * offline. Does NOT fire on the first connect, only on reconnects.
55
- *
56
- * A fresh closure each render is fine — it does not re-subscribe or fire
57
- * spuriously, so you do not need to memoize the callback.
58
- *
59
- * @param hub The hub path to watch.
60
- * @param callback Invoked after each successful reconnect.
61
- */
62
29
  function useOnReconnected(hub, callback) {
63
- const { registerReconnect } = useSignalR();
30
+ const { registerReconnect } = useInternalContext();
64
31
  useHubConsumer(hub);
65
32
  const cbRef = useLatest(callback);
66
33
  useEffect(() => registerReconnect(hub, () => cbRef.current()), [hub, registerReconnect, cbRef]);
67
34
  }
68
- /**
69
- * Subscribes to a typed server event for the lifetime of the component. The
70
- * handler's args are inferred from your contract for `(hub, event)`. The
71
- * subscription attaches once the hub is connected, re-attaches across
72
- * reconnects, and detaches on unmount.
73
- *
74
- * A fresh closure each render is fine — it does not re-subscribe, so you do
75
- * not need to memoize the handler.
76
- *
77
- * @param hub The hub path.
78
- * @param event The event name, a key of that hub's `events`.
79
- * @param handler Called with the event's typed args each time the server pushes it.
80
- */
81
35
  function useSignalREffect(hub, event, handler) {
82
- const { getConnection } = useSignalR();
83
- const status = useHubStatus(hub); // acquires lazy hub + re-renders on connect
36
+ const { subscribe } = useInternalContext();
37
+ useHubConsumer(hub);
84
38
  const handlerRef = useLatest(handler);
85
- useEffect(() => {
86
- const connection = getConnection(hub);
87
- if (!connection || status !== "connected")
88
- return;
89
- const listener = (...args) => handlerRef.current(...args);
90
- connection.on(event, listener);
91
- return () => connection.off(event, listener);
92
- }, [hub, event, status, getConnection, handlerRef]);
39
+ useEffect(() => subscribe(hub, event, (...args) => handlerRef.current(...args)), [hub, event, subscribe, handlerRef]);
93
40
  }
94
- /**
95
- * Returns a stable, typed function that invokes a hub method and resolves
96
- * with its return value. It waits, up to `timeout`, for the connection
97
- * before it invokes, so calling right after mount is safe.
98
- *
99
- * Special behavior:
100
- * - **Fails fast by default** (`retries: 0`): rethrows the raw server error,
101
- * so callers see the original.
102
- * - **Opt-in retry** for retriable failures (transport drops, timeouts),
103
- * with jittered backoff. Business errors (a `HubException` thrown while
104
- * still connected) are never retried.
105
- * - **At-least-once when retrying.** Enable `retries` only for IDEMPOTENT methods.
106
- * - **Auto-aborts** any in-flight call or retry loop on unmount, UNLESS
107
- * `keepAliveOnUnmount: true`. For a method invoked in an effect cleanup,
108
- * set that flag, or prefer {@link useSignalRTeardown}, which also handles
109
- * the hub-still-connecting race.
110
- *
111
- * @param hub The hub path.
112
- * @param method The method name, a key of that hub's `methods`.
113
- * @param options Optional `retries`, `timeout`, `backoff`, `isRetriable`, `keepAliveOnUnmount`.
114
- * @returns An async fn that takes the method's typed args and resolves to its typed return.
115
- * @throws The raw error when `retries === 0`. Otherwise an {@link InvokeError}
116
- * that wraps the last failure once attempts are exhausted.
117
- */
118
41
  function useSignalRInvoke(hub, method, options) {
119
- const { waitForConnection, getConnection } = useSignalR();
42
+ const { waitForConnection, getConnection, acquire, release } = useInternalContext();
120
43
  useHubConsumer(hub);
121
44
  const optsRef = useLatest(options);
122
45
  const scopeRef = useRef(null);
@@ -124,63 +47,31 @@ export function createSignalRHooks(ReactContext) {
124
47
  const scope = scopeRef.current;
125
48
  useEffect(() => () => {
126
49
  if (!optsRef.current?.keepAliveOnUnmount)
127
- scope.abortAll();
50
+ scope.abort();
128
51
  }, [optsRef, scope]);
129
- return useMemo(() => createInvoker({ waitForConnection, getConnection }, hub, method, () => optsRef.current, scope.track, scope.untrack), [waitForConnection, getConnection, hub, method, optsRef, scope]);
52
+ return useMemo(() => createInvoker({
53
+ target: { waitForConnection, getConnection, acquire, release },
54
+ hub,
55
+ method,
56
+ getOptions: () => optsRef.current,
57
+ getSignal: scope.signal,
58
+ }), [waitForConnection, getConnection, acquire, release, hub, method, optsRef, scope]);
130
59
  }
131
- /**
132
- * Returns a stable, typed fire-and-forget sender. Unlike {@link useSignalRInvoke},
133
- * it does NOT wait for the connection and does NOT return the method's
134
- * result. If the hub is not Connected, the call is dropped (resolves
135
- * `false`); otherwise it is dispatched (resolves `true`).
136
- *
137
- * Reads the connection at call time and never depends on render-time state,
138
- * so it is safe to capture in an unmount cleanup.
139
- *
140
- * @param hub The hub path.
141
- * @param method The method name, a key of that hub's `methods`.
142
- * @returns An async fn that takes the method's typed args and resolves
143
- * `true` if dispatched, `false` if dropped because it was not connected.
144
- */
145
60
  function useSignalRSend(hub, method) {
146
- const { getConnection } = useSignalR();
61
+ const { getConnection } = useInternalContext();
147
62
  useHubConsumer(hub);
148
- return useMemo(() => createSender(getConnection, hub, method), [getConnection, hub, method]);
63
+ return useMemo(() => createSender({ getConnection, hub, method }), [getConnection, hub, method]);
149
64
  }
150
- /**
151
- * Returns a stable, typed RELIABLE teardown sender, built for a method
152
- * invoked in an effect cleanup. Unlike {@link useSignalRSend}, which drops
153
- * a call if not yet connected, and {@link useSignalRInvoke}, which aborts
154
- * in-flight calls on unmount, the returned function:
155
- *
156
- * - **Survives the calling component's unmount.** It runs detached, not
157
- * tied to any effect or AbortController, so a call issued in cleanup
158
- * still lands.
159
- * - **Queues while connecting.** It waits, up to `timeout`, for the hub to
160
- * (re)connect, then sends, instead of dropping the call.
161
- * - **Holds a lazy hub open** until the flush completes, even when the
162
- * calling component was the last consumer — it acquires and releases
163
- * independently.
164
- * - **Is best-effort and fire-and-forget.** It resolves `true` once
165
- * dispatched, `false` if the hub never connected within `timeout`, and
166
- * never throws.
167
- *
168
- * Trade-off: under StrictMode's mount→cleanup→mount, the intermediate
169
- * teardown DOES fire, and the remount then re-runs setup. This is correct:
170
- * the server is never left in a stale joined state, at the cost of one
171
- * extra round-trip.
172
- *
173
- * @param hub The hub path.
174
- * @param method The teardown method name, a key of that hub's `methods`.
175
- * @param options Optional `timeout` in ms to wait for a connection. Default 10_000.
176
- * @returns An async fn that takes the method's typed args and resolves
177
- * `true` if dispatched, `false` if the hub never connected in time.
178
- */
179
65
  function useSignalRTeardown(hub, method, options) {
180
- const { acquire, release, waitForConnection } = useSignalR();
66
+ const { acquire, release, waitForConnection } = useInternalContext();
181
67
  useHubConsumer(hub);
182
68
  const optsRef = useLatest(options);
183
- return useMemo(() => createTeardownSender({ acquire, release, waitForConnection }, hub, method, () => optsRef.current), [acquire, release, waitForConnection, hub, method, optsRef]);
69
+ return useMemo(() => createTeardownSender({
70
+ target: { acquire, release, waitForConnection },
71
+ hub,
72
+ method,
73
+ getOptions: () => optsRef.current,
74
+ }), [acquire, release, waitForConnection, hub, method, optsRef]);
184
75
  }
185
76
  return {
186
77
  useSignalR,
@@ -2,4 +2,4 @@ import type { Context } from "react";
2
2
  import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
3
3
  import type { SignalRContextValue, SignalRProviderProps } from "../types.js";
4
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;
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<keyof T & `/${string}`>) => import("react").JSX.Element;
@@ -1,36 +1,37 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useEffect, useMemo, useRef } from "react";
2
+ import { useEffect, useRef } from "react";
3
3
  import { useLatest } from "../internal-hooks.js";
4
4
  import { createStatusStore } from "../status-store.js";
5
5
  import { createSignalRSession } from "@dammers/use-signalr-core";
6
6
  /** Builds the `SignalRProvider` component bound to one client's context. */
7
7
  export function createSignalRProvider(ReactContext, hubs, resolve) {
8
8
  return function SignalRProvider({ children, baseUrl, accessTokenFactory, enabled = true, connectionKey, onStatusChange, onError, }) {
9
- const statusStore = useRef(createStatusStore()).current;
10
- // Latest props via refs, so once-attached handlers call the current props.
11
9
  const tokenFactoryRef = useLatest(accessTokenFactory);
12
10
  const onStatusChangeRef = useLatest(onStatusChange);
13
11
  const onErrorRef = useLatest(onError);
14
- const session = useRef(createSignalRSession({
12
+ const sessionRef = useRef(null);
13
+ sessionRef.current ?? (sessionRef.current = createSignalRSession({
15
14
  hubs,
16
15
  resolve,
17
- statusStore,
16
+ statusStore: createStatusStore(),
18
17
  getAccessToken: () => tokenFactoryRef.current(),
19
18
  onStatusChange: (hub, status) => onStatusChangeRef.current?.(hub, status),
20
- onError: (hub, err) => onErrorRef.current?.(hub, err),
21
- })).current;
19
+ onError: (hub, err, info) => onErrorRef.current?.(hub, err, info),
20
+ }));
21
+ const session = sessionRef.current;
22
+ const stopPending = useRef(false);
22
23
  useEffect(() => {
23
- if (!enabled || !baseUrl) {
24
- session.stop();
25
- return;
26
- }
27
- session.start(baseUrl);
28
- return () => session.stop();
29
- // Rebuild only when the connection identity changes. tokenFactoryRef and
30
- // on*Ref are stable; props are read through .current.
31
- // eslint-disable-next-line react-hooks/exhaustive-deps
32
- }, [baseUrl, enabled, connectionKey]);
33
- const value = useMemo(() => session.context, [session]);
34
- return _jsx(ReactContext, { value: value, children: children });
24
+ stopPending.current = false;
25
+ session.update({ baseUrl, enabled, connectionKey });
26
+ return () => {
27
+ stopPending.current = true;
28
+ // StrictMode re-runs the effect synchronously, so a deferred stop can be cancelled.
29
+ queueMicrotask(() => {
30
+ if (stopPending.current)
31
+ session.stop();
32
+ });
33
+ };
34
+ }, [session, baseUrl, enabled, connectionKey]);
35
+ return _jsx(ReactContext, { value: session.context, children: children });
35
36
  };
36
37
  }
@@ -1,10 +1,5 @@
1
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
- */
2
+ /** External store for hub statuses, read with `useSyncExternalStore`. */
8
3
  export interface StatusStore<H extends string> extends StatusStoreBase<H> {
9
4
  subscribe: (hub: H, listener: () => void) => () => void;
10
5
  }
@@ -10,7 +10,7 @@ export function createStatusStore() {
10
10
  set.add(listener);
11
11
  return () => set.delete(listener);
12
12
  },
13
- get: (hub) => snapshot.get(hub) ?? "disconnected",
13
+ get: (hub) => snapshot.get(hub) ?? "idle",
14
14
  set: (hub, status) => {
15
15
  if (snapshot.get(hub) === status)
16
16
  return; // dedupe: skip a spurious notify
package/dist/types.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import type { ReactNode } from "react";
2
2
  import type { HubString, SignalRContract, SignalRProviderPropsBase, SignalRContextValueBase } from "@dammers/use-signalr-core";
3
3
  import type { StatusStore } from "./status-store.js";
4
- export type SignalRProviderProps = SignalRProviderPropsBase<ReactNode>;
4
+ export type SignalRProviderProps<THub extends HubString = HubString> = SignalRProviderPropsBase<THub> & {
5
+ /** The component tree that uses the hooks. */
6
+ children: ReactNode;
7
+ };
5
8
  export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dammers/use-signalr-react",
3
- "version": "0.5.0",
3
+ "version": "1.0.0",
4
4
  "description": "Fully-typed multi-hub SignalR provider + hooks for React: auto-reconnect, invoke retry, lazy hubs, live status.",
5
5
  "author": "Dammers",
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "url": "git+https://github.com/DammersCode/use-signalr.git",
10
10
  "directory": "packages/react"
11
11
  },
12
- "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/react#readme",
12
+ "homepage": "https://use-signalr.vercel.app/docs/react",
13
13
  "bugs": "https://github.com/DammersCode/use-signalr/issues",
14
14
  "keywords": [
15
15
  "signalr",
@@ -20,7 +20,7 @@
20
20
  "hooks"
21
21
  ],
22
22
  "engines": {
23
- "node": ">=18"
23
+ "node": ">=20.19"
24
24
  },
25
25
  "type": "module",
26
26
  "sideEffects": false,
@@ -29,8 +29,10 @@
29
29
  "exports": {
30
30
  ".": {
31
31
  "types": "./dist/index.d.ts",
32
- "import": "./dist/index.js"
33
- }
32
+ "import": "./dist/index.js",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "./package.json": "./package.json"
34
36
  },
35
37
  "files": [
36
38
  "dist"
@@ -45,17 +47,17 @@
45
47
  "test": "vitest run"
46
48
  },
47
49
  "dependencies": {
48
- "@dammers/use-signalr-core": "0.5.0"
50
+ "@dammers/use-signalr-core": "1.0.0"
49
51
  },
50
52
  "peerDependencies": {
51
- "@microsoft/signalr": ">=8",
52
- "react": ">=19"
53
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
54
+ "react": "^19.0.0"
53
55
  },
54
56
  "devDependencies": {
55
- "@microsoft/signalr": ">=8",
57
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
56
58
  "@testing-library/react": "^16.1.0",
57
- "@types/react": ">=19",
58
- "react": ">=19",
59
- "react-dom": ">=19"
59
+ "@types/react": "^19.0.0",
60
+ "react": "^19.0.0",
61
+ "react-dom": "^19.0.0"
60
62
  }
61
63
  }