react-wsclient 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,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ezekiel Williams
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # React WebSocket Client
2
+
3
+ An easy and flexible way to work with websockets in React.
4
+
5
+ ## Why?
6
+
7
+ There are already great libraries that handle websocket connectivity in React, but I didn't like the general opinion to force `flushSync` onto users. With rapid messaging over a websocket, taking advantage of React's batching for state updates can be a performance necessity. It also comes with some gotchas, but having the control is a good thing for intermediate to advanced developers.
8
+
9
+ ## Quick Start
10
+
11
+ **Add the provider**
12
+
13
+ ```jsx
14
+ createRoot(/** @type {HTMLElement} */ (document.getElementById('root'))).render(
15
+ <StrictMode>
16
+ <WSClientProvider url="ws://localhost:8080">
17
+ <App />
18
+ </WSClientProvider>
19
+ </StrictMode>,
20
+ );
21
+ ```
22
+
23
+ **Use the hook**
24
+
25
+ ```jsx
26
+ const App = () => {
27
+ const [message, setMessage] = useState('');
28
+
29
+ const { sendMessage } = useWsClient({
30
+ onMessage: (data) => {
31
+ setResponse(data.content);
32
+ },
33
+ });
34
+
35
+ const send = () => {
36
+ sendMessage('Hello websocket!');
37
+ };
38
+
39
+ return (
40
+ <div>
41
+ <button onClick={send}>Send</button>
42
+ <p>Response: {response}</p>
43
+ </div>
44
+ );
45
+ };
46
+ ```
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "react-wsclient",
3
+ "private": false,
4
+ "version": "1.0.0",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.js"
8
+ },
9
+ "files": [
10
+ "src"
11
+ ],
12
+ "dependencies": {
13
+ "react": "^19.2.4",
14
+ "react-dom": "^19.2.4"
15
+ },
16
+ "peerDependencies": {
17
+ "react": ">=19",
18
+ "react-dom": ">=19"
19
+ },
20
+ "devDependencies": {
21
+ "@types/react": "^19.2.7",
22
+ "@types/react-dom": "^19.2.3"
23
+ },
24
+ "scripts": {
25
+ "lint": "eslint ."
26
+ }
27
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * @typedef {object} Options
3
+ * @property {(data: any) => void} onMessage
4
+ * @property {(data: any) => boolean} [filter]
5
+ * @property {(e: Event) => void} [onOpen] Optional event handler when the connection opens.
6
+ * @property {(e: CloseEvent, manualDisconnect: boolean) => void} [onClose]
7
+ */
8
+
9
+ export class WSClient {
10
+ id = crypto.randomUUID();
11
+ /** @type {(() => Options)[]} */
12
+ subs = [];
13
+ /** @type {WebSocket | null} */
14
+ connection = null;
15
+ /** @type {string[]} */
16
+ messageQueue = [];
17
+ /** @type {string} */
18
+ url;
19
+ /** @type {boolean} */
20
+ useJson;
21
+ /** @type {(retryCount: number) => number} */
22
+ retryInterval;
23
+ /** @type {boolean} */
24
+ retry;
25
+ /** @type {boolean} */
26
+ manualDisconnect = false;
27
+ retryCount = 0;
28
+ /** @type {number} */
29
+ maxRetries;
30
+
31
+ /**
32
+ * @param {object} options
33
+ * @param {string} options.url
34
+ * @param {boolean} options.useJson
35
+ * @param {boolean} options.retry
36
+ * @param {(retryCount: number) => number} options.retryInterval
37
+ * @param {number} options.maxRetries
38
+ */
39
+ constructor({ url, useJson, retry, retryInterval, maxRetries }) {
40
+ this.url = url;
41
+ this.useJson = useJson;
42
+ this.retry = retry;
43
+ this.retryInterval = retryInterval;
44
+ this.maxRetries = maxRetries;
45
+ }
46
+
47
+ /**
48
+ * Sends data over the connection to the server.
49
+ * @param {string} data
50
+ */
51
+ send(data) {
52
+ if (this.connection && this.connection.readyState === WebSocket.OPEN) {
53
+ this.connection.send(data);
54
+ } else {
55
+ this.messageQueue.push(data);
56
+ }
57
+ }
58
+
59
+ /**
60
+ *
61
+ * @param {() => Options} subscriber
62
+ */
63
+ subscribe(subscriber) {
64
+ this.subs.push(subscriber);
65
+
66
+ return () => {
67
+ this.subs = this.subs.filter((sub) => sub !== subscriber);
68
+ };
69
+ }
70
+
71
+ connect() {
72
+ this.manualDisconnect = false;
73
+ if (this.connection !== null) {
74
+ return;
75
+ }
76
+
77
+ this.connection = new WebSocket(this.url);
78
+ this.#addListeners(this.connection);
79
+ }
80
+
81
+ get isConnected() {
82
+ return this.connection?.readyState === WebSocket.OPEN;
83
+ }
84
+
85
+ disconnect() {
86
+ this.manualDisconnect = true;
87
+
88
+ if (this.connection) {
89
+ this.connection?.close();
90
+
91
+ this.connection.onopen = null;
92
+ this.connection.onmessage = null;
93
+ this.connection.onclose = null;
94
+ this.connection.onerror = null;
95
+ this.connection = null;
96
+ }
97
+ }
98
+
99
+ /**
100
+ *
101
+ * @param {WebSocket} newConnection
102
+ */
103
+ #addListeners(newConnection) {
104
+ newConnection.onopen = (e) => {
105
+ this.#notifyOpen(e);
106
+ this.retryCount = 0;
107
+
108
+ let msg = this.messageQueue.shift();
109
+ while (msg !== undefined) {
110
+ this.connection?.send(msg);
111
+ msg = this.messageQueue.shift();
112
+ }
113
+ };
114
+
115
+ newConnection.onmessage = (/** @type {MessageEvent<string>} */ e) => {
116
+ let message;
117
+ if (this.useJson) {
118
+ try {
119
+ message = JSON.parse(e.data);
120
+ } catch (err) {
121
+ console.error('Failed to parse JSON message when useJson flag true.', err, e.data);
122
+ return;
123
+ }
124
+ } else {
125
+ message = e.data;
126
+ }
127
+
128
+ this.subs.forEach((getSub) => {
129
+ const sub = getSub();
130
+ if (!sub.filter || sub.filter(message)) {
131
+ sub.onMessage(message);
132
+ }
133
+ });
134
+ };
135
+
136
+ newConnection.onclose = (e) => {
137
+ this.#notifyClose(e, this.manualDisconnect);
138
+ if (this.manualDisconnect) {
139
+ return;
140
+ }
141
+
142
+ if (this.retry && this.retryCount < this.maxRetries) {
143
+ this.retryCount += 1;
144
+ const interval = this.retryInterval(this.retryCount);
145
+
146
+ window.setTimeout(() => {
147
+ this.connection = new WebSocket(this.url);
148
+ this.#addListeners(this.connection);
149
+ }, interval);
150
+ }
151
+ };
152
+
153
+ newConnection.onerror = (e) => {
154
+ console.error(`Error with websocket connection: `, e);
155
+ };
156
+ }
157
+
158
+ /**
159
+ *
160
+ * @param {Event} e
161
+ */
162
+ #notifyOpen(e) {
163
+ this.subs.forEach((getSub) => {
164
+ getSub().onOpen?.(e);
165
+ });
166
+ }
167
+
168
+ /**
169
+ *
170
+ * @param {CloseEvent} e
171
+ * @param {boolean} manualDisconnect
172
+ */
173
+ #notifyClose(e, manualDisconnect) {
174
+ this.subs.forEach((getSub) => {
175
+ getSub().onClose?.(e, manualDisconnect);
176
+ });
177
+ }
178
+ }
@@ -0,0 +1,6 @@
1
+ import { createContext } from 'react';
2
+ import { WSClient } from './WSClient';
3
+
4
+ /** @type {React.Context<WSClient | null>} */
5
+ // @ts-expect-error
6
+ export const WSClientContext = createContext(null);
@@ -0,0 +1,42 @@
1
+ import { useEffect, useMemo } from 'react';
2
+ import { WSClient } from './WSClient';
3
+ import { WSClientContext } from './WSClientContext';
4
+
5
+ /** @type {Map<string, WSClient>} */
6
+ // const clientMap = new Map();
7
+
8
+ /**
9
+ * @typedef {object} WSConfigProviderProps
10
+ * @property {React.ReactNode} children
11
+ * @property {string} url
12
+ * @property {boolean} [useJson=true]
13
+ * @property {boolean} [retry=true]
14
+ * @property {(retryCount: number) => number} [retryInterval]
15
+ * @property {number} [maxRetries=5]
16
+ */
17
+
18
+ /** @type {React.FC<WSConfigProviderProps>} */
19
+ const WSClientProvider = ({ children, url, useJson = true, retry = true, retryInterval, maxRetries = 5 }) => {
20
+ const client = useMemo(() => {
21
+ const effectiveRetryInterval = retryInterval ?? ((n) => n * n * 1000);
22
+ return new WSClient({
23
+ url,
24
+ retry,
25
+ retryInterval: effectiveRetryInterval,
26
+ maxRetries,
27
+ useJson,
28
+ });
29
+ }, [url, retry, retryInterval, maxRetries, useJson]);
30
+
31
+ useEffect(() => {
32
+ client.connect();
33
+
34
+ return () => {
35
+ client.disconnect();
36
+ };
37
+ }, [client]);
38
+
39
+ return <WSClientContext.Provider value={client}>{children}</WSClientContext.Provider>;
40
+ };
41
+
42
+ export default WSClientProvider;
package/src/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import { useWsClient } from './useWsClient';
2
+ import WSClientProvider from './WSClientProvider';
3
+
4
+ export { useWsClient, WSClientProvider };
@@ -0,0 +1,44 @@
1
+ import { useCallback, useContext, useEffect, useRef } from 'react';
2
+ import { WSClientContext } from './WSClientContext';
3
+
4
+ /**
5
+ * A hook that handles websocket connectivity
6
+ * @param {import('./WSClient').Options} options
7
+ */
8
+ export const useWsClient = (options) => {
9
+ const wsClient = useClientContext();
10
+ const optionsRef = useRef(options);
11
+ // eslint-disable-next-line react-hooks/refs
12
+ optionsRef.current = options;
13
+
14
+ /** @type {(data: string) => void} */
15
+ const sendMessage = useCallback(
16
+ (data) => {
17
+ wsClient.send(data);
18
+ },
19
+ [wsClient],
20
+ );
21
+
22
+ useEffect(() => {
23
+ const unsubscribe = wsClient.subscribe(() => optionsRef.current);
24
+
25
+ return () => {
26
+ unsubscribe();
27
+ };
28
+ }, [wsClient]);
29
+
30
+ return {
31
+ sendMessage,
32
+ isConnected: wsClient.isConnected,
33
+ reconnect: () => wsClient.connect(),
34
+ disconnect: () => wsClient.disconnect(),
35
+ };
36
+ };
37
+
38
+ const useClientContext = () => {
39
+ const client = useContext(WSClientContext);
40
+ if (client === null) {
41
+ throw new Error('useWsClient must be used within a WSClientProvider.');
42
+ }
43
+ return client;
44
+ };