react-realtime-hooks 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Artyom
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,474 @@
1
+ # react-realtime-hooks
2
+
3
+ Typed React hooks for realtime client state: WebSocket, SSE, reconnect, heartbeat, and online status.
4
+
5
+ `react-realtime-hooks` is built for apps that need transport state, retry strategy, and browser network signals without rewriting the same connection lifecycle in every component.
6
+
7
+ Live demo: https://volkov85.github.io/react-realtime-hooks/
8
+
9
+ ## Why This Package
10
+
11
+ - Realtime hooks usually stop at "open a socket". This package also models reconnect flow, heartbeat flow, browser online state, and transport snapshots.
12
+ - TypeScript support is first-class: generic payload types, custom parsers/serializers, and discriminated connection states.
13
+ - It is SSR-safe by default. The hooks avoid touching browser-only globals during server render.
14
+ - The package has no runtime dependencies beyond React.
15
+ - The repo is set up like a library product, not just a demo: tests, CI, publint, Changesets, and a demo app.
16
+
17
+ ## Features
18
+
19
+ - `useWebSocket`
20
+ - `useEventSource`
21
+ - `useReconnect`
22
+ - `useHeartbeat`
23
+ - `useOnlineStatus`
24
+ - Type-safe connection snapshots
25
+ - Reconnect/backoff helpers
26
+ - Browser API mocks in tests
27
+ - Demo app for manual verification
28
+ - Public GitHub Pages playground
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ npm install react-realtime-hooks
34
+ ```
35
+
36
+ Peer dependency:
37
+
38
+ - `react@^18.3.0 || ^19.0.0`
39
+
40
+ ## Quick Start
41
+
42
+ ```tsx
43
+ import { useWebSocket } from "react-realtime-hooks";
44
+
45
+ export const Notifications = () => {
46
+ const socket = useWebSocket<{ type: string; message: string }>({
47
+ url: "ws://localhost:8080",
48
+ reconnect: {
49
+ initialDelayMs: 1_000,
50
+ maxAttempts: 5
51
+ }
52
+ });
53
+
54
+ if (socket.status === "open") {
55
+ return <div>{socket.lastMessage?.message ?? "Connected"}</div>;
56
+ }
57
+
58
+ return <div>{socket.status}</div>;
59
+ };
60
+ ```
61
+
62
+ ## Links
63
+
64
+ - Demo: https://volkov85.github.io/react-realtime-hooks/
65
+ - Repository: https://github.com/volkov85/react-realtime-hooks
66
+
67
+ ## Examples
68
+
69
+ ### useOnlineStatus
70
+
71
+ ```tsx
72
+ import { useOnlineStatus } from "react-realtime-hooks";
73
+
74
+ export const NetworkIndicator = () => {
75
+ const network = useOnlineStatus({
76
+ trackTransitions: true
77
+ });
78
+
79
+ return (
80
+ <span>
81
+ {network.isOnline ? "Online" : "Offline"}
82
+ </span>
83
+ );
84
+ };
85
+ ```
86
+
87
+ ### useReconnect
88
+
89
+ ```tsx
90
+ import { useReconnect } from "react-realtime-hooks";
91
+
92
+ export const RetryPanel = () => {
93
+ const reconnect = useReconnect({
94
+ initialDelayMs: 1_000,
95
+ maxAttempts: 5,
96
+ jitterRatio: 0
97
+ });
98
+
99
+ return (
100
+ <button onClick={() => reconnect.schedule("manual")}>
101
+ Retry now
102
+ </button>
103
+ );
104
+ };
105
+ ```
106
+
107
+ ### useHeartbeat
108
+
109
+ ```tsx
110
+ import { useHeartbeat } from "react-realtime-hooks";
111
+
112
+ export const HeartbeatPanel = () => {
113
+ const heartbeat = useHeartbeat<string, string>({
114
+ intervalMs: 5_000,
115
+ matchesAck: (message) => message === "pong",
116
+ startOnMount: true,
117
+ timeoutMs: 2_000
118
+ });
119
+
120
+ return (
121
+ <div>
122
+ running: {String(heartbeat.isRunning)} | latency: {heartbeat.latencyMs ?? "n/a"}
123
+ </div>
124
+ );
125
+ };
126
+ ```
127
+
128
+ ### useWebSocket
129
+
130
+ ```tsx
131
+ import { useWebSocket } from "react-realtime-hooks";
132
+
133
+ type IncomingMessage = {
134
+ type: "chat" | "system";
135
+ text: string;
136
+ };
137
+
138
+ type OutgoingMessage = {
139
+ type: "ping" | "chat";
140
+ text?: string;
141
+ };
142
+
143
+ export const ChatSocket = () => {
144
+ const socket = useWebSocket<IncomingMessage, OutgoingMessage>({
145
+ url: "ws://localhost:8080",
146
+ heartbeat: {
147
+ intervalMs: 10_000,
148
+ matchesAck: (message) => message.type === "system" && message.text === "pong",
149
+ message: { type: "ping" },
150
+ timeoutMs: 3_000
151
+ },
152
+ parseMessage: (event) => JSON.parse(String(event.data)) as IncomingMessage,
153
+ reconnect: {
154
+ initialDelayMs: 1_000,
155
+ maxAttempts: null
156
+ }
157
+ });
158
+
159
+ return (
160
+ <button onClick={() => socket.send({ text: "Hello", type: "chat" })}>
161
+ Send
162
+ </button>
163
+ );
164
+ };
165
+ ```
166
+
167
+ ### useEventSource
168
+
169
+ ```tsx
170
+ import { useEventSource } from "react-realtime-hooks";
171
+
172
+ type FeedItem = {
173
+ id: string;
174
+ level: "info" | "warn";
175
+ text: string;
176
+ };
177
+
178
+ export const LiveFeed = () => {
179
+ const feed = useEventSource<FeedItem>({
180
+ events: ["notice"],
181
+ parseMessage: (event) => JSON.parse(event.data) as FeedItem,
182
+ reconnect: {
183
+ initialDelayMs: 1_000,
184
+ maxAttempts: 10
185
+ },
186
+ url: "http://localhost:8080/sse"
187
+ });
188
+
189
+ return (
190
+ <div>
191
+ {feed.lastEventName}: {feed.lastMessage?.text ?? "Waiting for updates"}
192
+ </div>
193
+ );
194
+ };
195
+ ```
196
+
197
+ ## API
198
+
199
+ ### useOnlineStatus
200
+
201
+ #### Options
202
+
203
+ | Option | Type | Default | Description |
204
+ | --- | --- | --- | --- |
205
+ | `initialOnline` | `boolean` | `true` | Fallback value when `navigator.onLine` is unavailable |
206
+ | `trackTransitions` | `boolean` | `true` | Tracks `lastChangedAt`, `wentOnlineAt`, `wentOfflineAt` |
207
+
208
+ #### Result
209
+
210
+ | Field | Type | Description |
211
+ | --- | --- | --- |
212
+ | `isOnline` | `boolean` | Current browser online state |
213
+ | `isSupported` | `boolean` | Whether `navigator.onLine` is available |
214
+ | `lastChangedAt` | `number \| null` | Timestamp of the last transition |
215
+ | `wentOnlineAt` | `number \| null` | Timestamp of the last online transition |
216
+ | `wentOfflineAt` | `number \| null` | Timestamp of the last offline transition |
217
+
218
+ ### useReconnect
219
+
220
+ #### Options
221
+
222
+ | Option | Type | Default | Description |
223
+ | --- | --- | --- | --- |
224
+ | `enabled` | `boolean` | `true` | Enables scheduling attempts |
225
+ | `initialDelayMs` | `number` | `1000` | Delay for the first attempt |
226
+ | `maxDelayMs` | `number` | `30000` | Delay cap |
227
+ | `backoffFactor` | `number` | `2` | Exponential multiplier |
228
+ | `jitterRatio` | `number` | `0.2` | Randomized variance ratio |
229
+ | `maxAttempts` | `number \| null` | `null` | Max attempts, `null` means unlimited |
230
+ | `getDelayMs` | `ReconnectDelayStrategy` | `undefined` | Custom delay strategy |
231
+ | `resetOnSuccess` | `boolean` | `true` | Resets attempt count after success |
232
+ | `onSchedule` | `(attempt) => void` | `undefined` | Called when an attempt is scheduled |
233
+ | `onCancel` | `() => void` | `undefined` | Called when scheduling is canceled |
234
+ | `onReset` | `() => void` | `undefined` | Called when state is reset |
235
+
236
+ #### Result
237
+
238
+ | Field | Type | Description |
239
+ | --- | --- | --- |
240
+ | `status` | `"idle" \| "scheduled" \| "running" \| "stopped"` | Current reconnect state |
241
+ | `attempt` | `number` | Current attempt number |
242
+ | `nextDelayMs` | `number \| null` | Delay of the scheduled attempt |
243
+ | `isActive` | `boolean` | `true` when scheduled or running |
244
+ | `isScheduled` | `boolean` | `true` when waiting for the next attempt |
245
+ | `schedule` | `(trigger?) => void` | Schedules an attempt |
246
+ | `cancel` | `() => void` | Cancels the current schedule |
247
+ | `reset` | `() => void` | Resets attempts and status |
248
+ | `markConnected` | `() => void` | Marks the transport as restored |
249
+
250
+ ### useHeartbeat
251
+
252
+ #### Options
253
+
254
+ | Option | Type | Default | Description |
255
+ | --- | --- | --- | --- |
256
+ | `enabled` | `boolean` | `true` | Enables the heartbeat loop |
257
+ | `intervalMs` | `number` | Required | Beat interval |
258
+ | `timeoutMs` | `number` | `undefined` | Timeout before `hasTimedOut` becomes `true` |
259
+ | `message` | `TOutgoing \| (() => TOutgoing)` | `undefined` | Optional heartbeat payload |
260
+ | `beat` | `() => void \| boolean \| Promise<void \| boolean>` | `undefined` | Custom beat side effect |
261
+ | `matchesAck` | `(message) => boolean` | `undefined` | Ack matcher |
262
+ | `startOnMount` | `boolean` | `true` | Starts immediately |
263
+ | `onBeat` | `() => void` | `undefined` | Called on every beat |
264
+ | `onTimeout` | `() => void` | `undefined` | Called on timeout |
265
+
266
+ #### Result
267
+
268
+ | Field | Type | Description |
269
+ | --- | --- | --- |
270
+ | `isRunning` | `boolean` | Whether the loop is active |
271
+ | `hasTimedOut` | `boolean` | Whether the latest beat timed out |
272
+ | `lastBeatAt` | `number \| null` | Last beat timestamp |
273
+ | `lastAckAt` | `number \| null` | Last ack timestamp |
274
+ | `latencyMs` | `number \| null` | Ack latency |
275
+ | `start` | `() => void` | Starts the loop |
276
+ | `stop` | `() => void` | Stops the loop |
277
+ | `beat` | `() => void` | Triggers a manual beat |
278
+ | `notifyAck` | `(message) => boolean` | Applies an incoming ack message |
279
+
280
+ ### useWebSocket
281
+
282
+ #### Options
283
+
284
+ | Option | Type | Default | Description |
285
+ | --- | --- | --- | --- |
286
+ | `url` | `UrlProvider` | Required | String, `URL`, or lazy URL factory |
287
+ | `protocols` | `string \| string[]` | `undefined` | WebSocket subprotocols |
288
+ | `connect` | `boolean` | `true` | Auto-connect on mount |
289
+ | `binaryType` | `BinaryType` | `"blob"` | Socket binary mode |
290
+ | `parseMessage` | `(event) => TIncoming` | raw `event.data` | Incoming parser |
291
+ | `serializeMessage` | `(message) => ...` | JSON/string passthrough | Outgoing serializer |
292
+ | `reconnect` | `false \| UseReconnectOptions` | enabled | Reconnect configuration |
293
+ | `heartbeat` | `false \| UseHeartbeatOptions` | disabled unless configured | Heartbeat configuration |
294
+ | `shouldReconnect` | `(event) => boolean` | `true` | Reconnect gate on close |
295
+ | `onOpen` | `(event, socket) => void` | `undefined` | Open callback |
296
+ | `onMessage` | `(message, event) => void` | `undefined` | Message callback |
297
+ | `onError` | `(event) => void` | `undefined` | Error callback |
298
+ | `onClose` | `(event) => void` | `undefined` | Close callback |
299
+
300
+ #### Result
301
+
302
+ | Field | Type | Description |
303
+ | --- | --- | --- |
304
+ | `status` | connection union | `idle`, `connecting`, `open`, `closing`, `closed`, `reconnecting`, `error` |
305
+ | `socket` | `WebSocket \| null` | Current transport instance |
306
+ | `lastMessage` | `TIncoming \| null` | Last parsed message |
307
+ | `lastCloseEvent` | `CloseEvent \| null` | Last close event |
308
+ | `lastError` | `Event \| null` | Last error |
309
+ | `bufferedAmount` | `number` | Current socket buffer size |
310
+ | `reconnectState` | reconnect snapshot or `null` | Current reconnect data |
311
+ | `heartbeatState` | heartbeat snapshot or `null` | Current heartbeat data |
312
+ | `open` | `() => void` | Manual connect |
313
+ | `close` | `(code?, reason?) => void` | Manual close |
314
+ | `reconnect` | `() => void` | Manual reconnect |
315
+ | `send` | `(message) => boolean` | Sends an outgoing payload |
316
+
317
+ ### useEventSource
318
+
319
+ #### Options
320
+
321
+ | Option | Type | Default | Description |
322
+ | --- | --- | --- | --- |
323
+ | `url` | `UrlProvider` | Required | String, `URL`, or lazy URL factory |
324
+ | `withCredentials` | `boolean` | `false` | Passes credentials to `EventSource` |
325
+ | `connect` | `boolean` | `true` | Auto-connect on mount |
326
+ | `events` | `readonly string[]` | `undefined` | Named SSE events to subscribe to |
327
+ | `parseMessage` | `(event) => TMessage` | raw `event.data` | Incoming parser |
328
+ | `reconnect` | `false \| UseReconnectOptions` | enabled | Reconnect configuration |
329
+ | `shouldReconnect` | `(event) => boolean` | `true` | Reconnect gate on error |
330
+ | `onOpen` | `(event, source) => void` | `undefined` | Open callback |
331
+ | `onMessage` | `(message, event) => void` | `undefined` | Default `message` callback |
332
+ | `onError` | `(event) => void` | `undefined` | Error callback |
333
+ | `onEvent` | `(eventName, message, event) => void` | `undefined` | Named event callback |
334
+
335
+ #### Result
336
+
337
+ | Field | Type | Description |
338
+ | --- | --- | --- |
339
+ | `status` | connection union | `idle`, `connecting`, `open`, `closing`, `closed`, `reconnecting`, `error` |
340
+ | `eventSource` | `EventSource \| null` | Current transport instance |
341
+ | `lastEventName` | `string \| null` | Last SSE event name |
342
+ | `lastMessage` | `TMessage \| null` | Last parsed payload |
343
+ | `lastError` | `Event \| null` | Last error |
344
+ | `reconnectState` | reconnect snapshot or `null` | Current reconnect data |
345
+ | `open` | `() => void` | Manual connect |
346
+ | `close` | `() => void` | Manual close |
347
+ | `reconnect` | `() => void` | Manual reconnect |
348
+
349
+ ## Status Model
350
+
351
+ The transport hooks return discriminated connection snapshots:
352
+
353
+ - `open`: connected
354
+ - `connecting`: opening the first connection
355
+ - `reconnecting`: reconnect flow is in progress
356
+ - `closing`: explicit close is in progress
357
+ - `closed`: transport was explicitly closed or cannot continue
358
+ - `idle`: auto-connect is disabled and nothing is currently opening
359
+ - `error`: the hook encountered an unrecoverable parse/runtime error
360
+
361
+ ## Limitations And Edge Cases
362
+
363
+ - `useEventSource` is receive-only by design. SSE is not a bidirectional transport.
364
+ - `useWebSocket` heartbeat logic is client-side. It does not define your server ping/pong protocol for you.
365
+ - If `parseMessage` throws, the hook moves into `error` and stores `lastError`.
366
+ - `connect: false` means the hook stays idle until `open()` is called.
367
+ - Manual `close()` is sticky: the hook stays closed until you call `open()` or `reconnect()`.
368
+ - On the server, transport hooks do not open real connections. They stay SSR-safe and connect only in the browser.
369
+ - Browser-native `WebSocket` and `EventSource` behavior still applies: proxy issues, auth constraints, and network policies are outside the hook’s control.
370
+ - `EventSource` named events are additive. The hook always listens to the default `message` channel.
371
+ - No transport polyfills are bundled. If you target unsupported environments, provide your own runtime/polyfill.
372
+
373
+ ## Testing
374
+
375
+ The package includes behavior tests for:
376
+
377
+ - connect / disconnect / reconnect
378
+ - exponential backoff
379
+ - cleanup of timers and listeners
380
+ - heartbeat start / stop / timeout
381
+ - browser offline / online transitions
382
+ - invalid payload / parse errors
383
+ - manual reconnect / manual close
384
+
385
+ `WebSocket` and `EventSource` are tested through mocked browser APIs.
386
+
387
+ ## Demo
388
+
389
+ Live playground:
390
+
391
+ - https://volkov85.github.io/react-realtime-hooks/
392
+
393
+ Run the local playground:
394
+
395
+ ```bash
396
+ npm run demo
397
+ ```
398
+
399
+ The demo includes separate blocks for:
400
+
401
+ - `useOnlineStatus`
402
+ - `useReconnect`
403
+ - `useHeartbeat`
404
+ - `useWebSocket`
405
+ - `useEventSource`
406
+
407
+ Notes:
408
+
409
+ - `useWebSocket` and `useEventSource` are exposed as playground blocks with manual URL input.
410
+ - Browser-only hooks still require real endpoints if you want to test transport connectivity in the hosted demo.
411
+
412
+ ## Development
413
+
414
+ Available scripts:
415
+
416
+ ```bash
417
+ npm run build
418
+ npm run demo
419
+ npm run demo:build
420
+ npm run lint
421
+ npm run typecheck
422
+ npm run test
423
+ npm run publint
424
+ ```
425
+
426
+ ## Changelog And Releases
427
+
428
+ This repo uses Changesets for versioning, changelog generation, and npm publishing.
429
+
430
+ ### Local workflow
431
+
432
+ Create a changeset for user-facing changes:
433
+
434
+ ```bash
435
+ npm run changeset
436
+ ```
437
+
438
+ Version packages locally:
439
+
440
+ ```bash
441
+ npm run version-packages
442
+ ```
443
+
444
+ Publish manually:
445
+
446
+ ```bash
447
+ npm run release
448
+ ```
449
+
450
+ ### CI release workflow
451
+
452
+ - Feature work lands in `main`
453
+ - A Changesets release PR is created automatically
454
+ - When that PR is merged, Changesets publishes to npm
455
+ - Changelog entries are generated from the changeset summaries
456
+
457
+ Required GitHub secrets:
458
+
459
+ - `NPM_TOKEN`
460
+
461
+ ## CI
462
+
463
+ Quality gate runs on pushes and pull requests:
464
+
465
+ - `npm run typecheck`
466
+ - `npm run lint`
467
+ - `npm run test`
468
+ - `npm run build`
469
+ - `npm run demo:build`
470
+ - `npm run publint`
471
+
472
+ ## License
473
+
474
+ MIT