
Product
Microsoft Teams Notifications Are Now Available in Socket
Socket can now send alerts and supply chain attack notifications to Microsoft Teams, with filters that route the right updates to each channel.
@gedeagas/react-universal-websocket
Advanced tools
react-universal-websocket This library is compatible with both React and React Native, offering powerful and flexible React hooks to simplify the management of WebSocket connections. It features seamless WebSocket integration within your applications, including capabilities like automatic reconnection, offline message queuing, and the ability to share WebSocket connections across components. Additionally, it provides typed support for both TypeScript and Flow, ensuring robust type safety for your projects.
🇨🇳 中文文档
To install the useWebSocket hook, you can use npm or yarn:
npm install @gedeagas/react-universal-websocket
Or using Yarn:
yarn add @gedeagas/react-universal-websocket
Here's a basic example of how to use the useWebSocket hook in a React component:
import React, { useEffect } from 'react';
import { useWebSocket, ReadyState } from '@gedeagas/react-universal-websocket';
const WebSocketExample = () => {
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket');
useEffect(() => {
if (lastMessage !== null) {
console.log('Received message:', lastMessage.data);
}
}, [lastMessage]);
const handleClick = () => {
sendMessage('Hello, server!');
};
const connectionStatus = {
[ReadyState.CONNECTING]: 'Connecting',
[ReadyState.OPEN]: 'Open',
[ReadyState.CLOSING]: 'Closing',
[ReadyState.CLOSED]: 'Closed',
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
}[readyState];
return (
<div>
<button onClick={handleClick}>Send Message</button>
<p>Connection Status: {connectionStatus}</p>
{lastMessage && <p>Last message: {lastMessage.data}</p>}
</div>
);
};
export default WebSocketExample;
The useWebSocket hook accepts a configuration object with various options to customize the behavior of the WebSocket connection:
queryParams (QueryParams): An object containing query parameters to append to the WebSocket URL.protocols (string | string[]): A string or array of strings representing the subprotocols.share (boolean): If true, allows sharing of the WebSocket instance among multiple hooks.onOpen (function): A callback function for when the WebSocket connection opens.onClose (function): A callback function for when the WebSocket connection closes.onMessage (function): A callback function for handling incoming messages.onError (function): A callback function for handling errors.onReconnectStop (function): A callback function called when reconnection attempts stop.shouldReconnect (function): A function that determines whether to attempt reconnection.reconnectInterval (number | function): The interval between reconnection attempts.reconnectAttempts (number): The maximum number of reconnection attempts allowed.filter (function): A function to filter incoming messages.retryOnError (boolean): If true, retries connection on error.skipAssert (boolean): If true, skips WebSocket assertion checks.heartbeat (boolean | HeartbeatOptions): Enables heartbeat messages to keep the connection alive.Here's a comprehensive documentation for the useWebSocket hook options, along with examples for each. This should help developers understand and utilize the different configuration options available.
queryParamsAn object containing query parameters to append to the WebSocket URL.
{ [key: string]: string | number }Example:
const options = {
queryParams: { token: 'abcd1234' },
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
protocolsA string or array of strings representing the subprotocols.
string | string[]Example:
const options = {
protocols: ['protocolOne', 'protocolTwo'],
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
shareIf true, allows sharing of the WebSocket instance among multiple hooks.
booleanfalseExample:
const options = {
share: true,
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
onOpenA callback function for when the WebSocket connection opens.
(event: WebSocketEventMap["open"]) => voidExample:
const options = {
onOpen: (event) => console.log('Connection opened!', event),
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
onCloseA callback function for when the WebSocket connection closes.
(event: WebSocketEventMap["close"]) => voidExample:
const options = {
onClose: (event) => console.log('Connection closed!', event),
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
onMessageA callback function for handling incoming messages.
(event: WebSocketEventMap["message"]) => voidExample:
const options = {
onMessage: (event) => console.log('Message received!', event.data),
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
onErrorA callback function for handling errors.
(event: WebSocketEventMap["error"]) => voidExample:
const options = {
onError: (event) => console.log('Error occurred!', event),
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
onReconnectStopA callback function called when reconnection attempts stop.
(numAttempts: number) => voidExample:
const options = {
onReconnectStop: (numAttempts) => console.log(`Reconnection stopped after ${numAttempts} attempts`),
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
shouldReconnectA function that determines whether to attempt reconnection.
(event: WebSocketEventMap["close"]) => booleanExample:
const options = {
shouldReconnect: (event) => true, // Always attempt to reconnect
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
reconnectIntervalThe interval between reconnection attempts.
number | (lastAttemptNumber: number) => numberExample:
const options = {
reconnectInterval: 5000, // 5 seconds
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
reconnectAttemptsThe maximum number of reconnection attempts allowed.
numberExample:
const options = {
reconnectAttempts: 3, // Max 3 reconnection attempts
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
filterA function to filter incoming messages.
(message: WebSocketEventMap["message"]) => booleanExample:
const options = {
filter: (message) => message.data !== 'ignore', // Ignore messages with data 'ignore'
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
retryOnErrorIf true, retries connection on error.
booleanfalseExample:
const options = {
retryOnError: true,
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
skipAssertIf true, skips WebSocket assertion checks.
booleanfalseExample:
const options = {
skipAssert: true,
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
heartbeatEnables heartbeat messages to keep the connection alive.
boolean | HeartbeatOptionsExample:
const options = {
heartbeat: {
message: 'ping',
returnMessage: 'pong',
timeout: 3000, // 3 seconds
interval: 10000, // 10 seconds
},
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
Here’s a complete example using several options together:
import useWebSocket from 'react-use-websocket';
function App() {
const options = {
queryParams: { token: 'abcd1234' },
protocols: ['protocolOne', 'protocolTwo'],
share: true,
onOpen: (event) => console.log('Connection opened!', event),
onClose: (event) => console.log('Connection closed!', event),
onMessage: (event) => console.log('Message received!', event.data),
onError: (event) => console.log('Error occurred!', event),
onReconnectStop: (numAttempts) => console.log(`Reconnection stopped after ${numAttempts} attempts`),
shouldReconnect: (event) => true, // Always attempt to reconnect
reconnectInterval: (attemptNumber) => Math.min(Math.pow(2, attemptNumber) * 1000, 10000), // Exponential backoff
reconnectAttempts: 10, // Max 10 reconnection attempts
filter: (message) => message.data !== 'ignore', // Ignore messages with data 'ignore'
retryOnError: true,
skipAssert: true,
heartbeat: {
message: 'ping',
returnMessage: 'pong',
timeout: 3000, // 3 seconds
interval: 10000, // 10 seconds
},
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
return (
<div>
<p>Ready State: {readyState}</p>
<p>Last Message: {lastMessage ? lastMessage.data : 'No message yet'}</p>
<button onClick={() => sendMessage('Hello WebSocket!')}>Send Message</button>
</div>
);
}
export default App;
This documentation and the accompanying examples should help you understand and leverage the various options provided by the useWebSocket hook.
The useWebSocket hook provides the following API:
sendMessage: A function to send a message to the WebSocket server.sendJsonMessage: A function to send a JSON message to the WebSocket server.lastMessage: The last message received from the WebSocket server.lastJsonMessage: The last parsed JSON message received from the WebSocket server.readyState: The current state of the WebSocket connection.getWebSocket: A function to get the current WebSocket instance.string, ArrayBuffer, SharedArrayBuffer, Blob, or ArrayBufferView.To share a WebSocket connection among multiple components, set the share option to true. This ensures that a single WebSocket instance is reused, reducing the overhead of multiple connections.
const options = {
share: true,
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
Heartbeats can keep the connection alive by sending periodic messages. Use the heartbeat option to enable and configure heartbeats:
const options = {
heartbeat: {
message: 'ping', // Message sent as heartbeat
returnMessage: 'pong', // Expected return message
timeout: 10000, // Time to wait for return message
interval: 30000, // Interval between heartbeats
},
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://example.com/socket', options);
When dealing with WebSocket connections, it's important to handle reconnections gracefully to ensure reliability. This can be achieved using the shouldReconnect, reconnectInterval, and reconnectAttempts options.
Here's an example of how you can configure these options:
Alternatively, you can provide a function for reconnectInterval that accepts the nth last attempt as a parameter and returns a number. This can be useful for employing more advanced reconnect strategies like Exponential Backoff:
const exponentialBackoffOptions = {
shouldReconnect: (closeEvent) => true,
reconnectAttempts: 10, // Max 10 reconnection attempts
// attemptNumber starts at 0, resulting in a pattern of 1 second, 2 seconds, 4 seconds, 8 seconds, and then caps at 10 seconds
reconnectInterval: (attemptNumber) =>
Math.min(Math.pow(2, attemptNumber) * 1000, 10000),
};
const { sendMessage, lastMessage, readyState } = useWebSocket(
'wss://echo.websocket.org',
exponentialBackoffOptions
);
Another algorithm for reconnection is the Fibonacci Backoff, which uses the Fibonacci sequence to determine the wait time between reconnections. Here's how you can implement it:
const fibonacciBackoffOptions = {
shouldReconnect: (closeEvent) => true,
reconnectAttempts: 10, // Max 10 reconnection attempts
reconnectInterval: (attemptNumber) => {
const fibonacci = (n) => {
if (n <= 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
};
// Cap at 60 seconds
return Math.min(fibonacci(attemptNumber + 1) * 1000, 60000);
},
};
const { sendMessage, lastMessage, readyState } = useWebSocket(
'wss://echo.websocket.org',
fibonacciBackoffOptions
);
By customizing the reconnectInterval function, you can control the reconnection strategy and improve the reliability and performance of your WebSocket connections based on your application's needs.
This project is a fork of react-use-websocket and is also inspired by react-native-reconnecting-websocket. We extend our gratitude to the authors and contributors of these projects for their excellent work and inspiration.
Contributions are welcome! Please feel free to submit a pull request or open an issue.
git checkout -b feature-branch).git commit -m 'Add new feature').git push origin feature-branch).This project is licensed under the MIT License. See the LICENSE file for more information.
FAQs
Universal Websocket Hooks for React & React Native
We found that @gedeagas/react-universal-websocket demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.

Product
Socket can now send alerts and supply chain attack notifications to Microsoft Teams, with filters that route the right updates to each channel.

Security News
pnpm 12 rewrites the package manager in Rust, cutting install times by up to 90% while preserving pnpm 11 workflows and lockfiles.

Security News
Socket CTO Ahmad Nassri joins AppSec leaders at Black Hat to discuss active malware, package manager risks, and software supply chain defense.