### Install react-use-websocket for React 18 or older versions
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Instructions for installing the react-use-websocket library. For React 18, use the latest version. For older React versions (prior to 18), install version 3.0.0.
```bash
npm install --save react-use-websocket@3.0.0
//or
yarn add react-use-websocket@3.0.0
```
--------------------------------
### Install react-use-websocket
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
This command installs the react-use-websocket package using npm. It's the first step to integrate WebSocket functionality into your React project.
```sh
npm install react-use-websocket
```
--------------------------------
### Get WebSocket Instance and Interact (JavaScript)
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Demonstrates how to obtain a WebSocket instance (or a proxy if shared) and interact with its properties and methods. Shows how to access properties like `binaryType` and attempts to modify immutable properties or call protected methods, illustrating the library's safeguards.
```javascript
const { sendMessage, lastMessage, readyState, getWebSocket } = useWebSocket(
'wss://echo.websocket.org',
{ share: true }
);
useEffect(() => {
console.log(getWebSocket().binaryType);
//=> 'blob'
//Change binaryType property of WebSocket
getWebSocket().binaryType = 'arraybuffer';
console.log(getWebSocket().binaryType);
//=> 'arraybuffer'
//Attempt to change event handler
getWebSocket().onmessage = console.log;
//=> A warning is logged to console: 'The WebSocket\'s event handlers should be defined through the options object passed into useWebSocket.'
//Attempt to change an immutable property
getWebSocket().url = 'www.google.com';
console.log(getWebSocket().url);
//=> 'wss://echo.websocket.org'
//Attempt to call webSocket#send
getWebSocket().send('Hello from WebSocket');
//=> No message is sent, and no error thrown (a no-op function was returned), but an error will be logged to console: 'Calling methods directly on the WebSocket is not supported at this moment. You must use the methods returned by useWebSocket.'
}, []);
```
--------------------------------
### WebSocket Connection with Query Parameters
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
This example demonstrates how to append query parameters to a WebSocket URL for authentication, room selection, or other server-side routing needs. It uses the `useWebSocket` hook and `useMemo` to dynamically generate query parameters. Changing these parameters triggers a reconnection with the updated URL. Dependencies include 'react' and 'react-use-websocket'.
```javascript
import React, { useState, useMemo } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const MultiRoomChat = () => {
const [userId] = useState(12345);
const [roomId, setRoomId] = useState(1);
const [sessionToken] = useState('abc123xyz789');
const socketUrl = 'wss://chat.example.com/ws';
// Query params will be appended: wss://chat.example.com/ws?user_id=12345&room_id=1&token=abc123xyz789
const queryParams = useMemo(() => ({
user_id: userId,
room_id: roomId,
token: sessionToken,
timestamp: Date.now()
}), [userId, roomId, sessionToken]);
const {
sendJsonMessage,
lastJsonMessage,
readyState
} = useWebSocket(socketUrl, {
queryParams,
shouldReconnect: () => true
});
const switchRoom = (newRoomId) => {
// Changing queryParams will trigger reconnection with new URL
setRoomId(newRoomId);
};
return (
Current Room: {roomId}
Status: {ReadyState[readyState]}
{lastJsonMessage && (
{lastJsonMessage.user}: {lastJsonMessage.text}
)}
);
};
```
--------------------------------
### Manage Multiple WebSocket Connections with react-use-websocket
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
This example illustrates how to manage and reset multiple WebSocket connections simultaneously using `resetGlobalState`. It demonstrates resetting individual connections by URL, resetting all active connections by calling `resetGlobalState()` without arguments, and selectively resetting connections based on specific criteria.
```javascript
// Multi-connection cleanup example
export const MultiConnectionManager = () => {
const connections = [
'wss://api.example.com/stream1',
'wss://api.example.com/stream2',
'wss://api.example.com/stream3'
];
const ws1 = useWebSocket(connections[0], { share: true });
const ws2 = useWebSocket(connections[1], { share: true });
const ws3 = useWebSocket(connections[2], { share: true });
const resetSingleConnection = (url) => {
console.log(`Resetting connection: ${url}`);
resetGlobalState(url);
};
const resetAllConnections = () => {
console.log('Resetting all connections');
resetGlobalState(); // No URL parameter = reset all
};
const resetSpecificConnections = () => {
// Reset only certain connections
connections.forEach(url => {
if (url.includes('stream2')) {
resetGlobalState(url);
}
});
};
return (
Connection Manager
{connections.map((url, idx) => (
Connection {idx + 1}: {url}
))}
);
};
```
--------------------------------
### React WebSocket Demo Implementation
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
An example React component demonstrating the use of the useWebSocket hook. It connects to a WebSocket server, sends messages, tracks connection status, and displays a history of received messages. It utilizes state management for socket URL and message history, and useCallback for memoizing event handlers.
```jsx
import React, { useState, useCallback, useEffect } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const WebSocketDemo = () => {
//Public API that will echo messages sent to it back to the client
const [socketUrl, setSocketUrl] = useState('wss://echo.websocket.org');
const [messageHistory, setMessageHistory] =
useState < MessageEvent < any > [] > [];
const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);
useEffect(() => {
if (lastMessage !== null) {
setMessageHistory((prev) => prev.concat(lastMessage));
}
}, [lastMessage]);
const handleClickChangeSocketUrl = useCallback(
() => setSocketUrl('wss://demos.kaazing.com/echo'),
[]
);
const handleClickSendMessage = useCallback(() => sendMessage('Hello'), []);
const connectionStatus = {
[ReadyState.CONNECTING]: 'Connecting',
[ReadyState.OPEN]: 'Open',
[ReadyState.CLOSING]: 'Closing',
[ReadyState.CLOSED]: 'Closed',
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
}[readyState];
return (
The WebSocket is currently {connectionStatus}
{lastMessage ? Last message: {lastMessage.data} : null}
);
};
```
--------------------------------
### Control WebSocket Connection with Feature Flags (React)
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
This example shows how to manage WebSocket connections based on feature flags. The connection is established only if at least one feature is enabled. Query parameters are dynamically added to the WebSocket URL based on the enabled features, allowing the server to filter messages accordingly. This approach is useful for enabling real-time features on demand.
```javascript
// Example: Feature-flag controlled connection
export const FeatureFlagConnection = () => {
const [features, setFeatures] = useState({
realtimeUpdates: false,
notifications: false,
analytics: false
});
const socketUrl = 'wss://api.example.com/features';
const shouldConnect = Object.values(features).some(enabled => enabled);
const { lastJsonMessage, readyState } = useWebSocket(
socketUrl,
{
queryParams: {
// Only subscribe to enabled features
features: Object.entries(features)
.filter(([_, enabled]) => enabled)
.map(([feature, _]) => feature)
.join(',')
}
},
shouldConnect
);
const toggleFeature = (featureName) => {
setFeatures(prev => ({
...prev,
[featureName]: !prev[featureName]
}));
};
return (
);
};
```
--------------------------------
### Share WebSocket Connections Across Components (JavaScript)
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
This example shows how multiple React components can share a single WebSocket connection to the same URL using the `share: true` option. This reduces resource usage and maintains consistent state. Components can filter messages based on type using the `filter` option.
```javascript
import React from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
// Component 1: Chat messages
export const ChatMessages = () => {
const { lastJsonMessage } = useWebSocket('wss://chat.example.com', {
share: true,
filter: (message) => {
try {
const data = JSON.parse(message.data);
return data.type === 'CHAT_MESSAGE';
} catch {
return false;
}
}
});
return (
);
};
// Component 3: Control panel with send capability
export const ChatControl = () => {
const { sendJsonMessage, readyState } = useWebSocket('wss://chat.example.com', {
share: true
});
return (
);
};
// All three components share the same WebSocket connection
export const App = () => (
);
```
--------------------------------
### Control WebSocket Connection with Authentication and Pausing (React)
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
This example demonstrates how to conditionally connect to a WebSocket server based on authentication status and a pause flag. It uses the `react-use-websocket` hook, passing a boolean `shouldConnect` as the third argument to control the connection lifecycle. The connection automatically opens when `shouldConnect` becomes true and closes when it becomes false. The `shouldReconnect` option is also configured to respect these conditions.
```javascript
import React, { useState, useCallback } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const ConditionalConnectionComponent = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const [socketUrl, setSocketUrl] = useState('wss://api.example.com/stream');
// Third parameter controls connection
const shouldConnect = isAuthenticated && !isPaused;
const {
sendMessage,
lastMessage,
readyState
} = useWebSocket(
socketUrl,
{
onOpen: () => console.log('Connected'),
onClose: () => console.log('Disconnected'),
shouldReconnect: (closeEvent) => isAuthenticated && !isPaused
},
shouldConnect // Connection control parameter
);
const login = useCallback(() => {
// Simulate authentication
console.log('Logging in...');
setIsAuthenticated(true);
// Connection will automatically open
}, []);
const logout = useCallback(() => {
console.log('Logging out...');
setIsAuthenticated(false);
// Connection will automatically close
}, []);
const pauseConnection = useCallback(() => {
console.log('Pausing connection...');
setIsPaused(true);
// Connection will close but can be resumed
}, []);
const resumeConnection = useCallback(() => {
console.log('Resuming connection...');
setIsPaused(false);
// Connection will reopen if authenticated
}, []);
const switchServer = useCallback((newUrl) => {
console.log(`Switching to ${newUrl}`);
setSocketUrl(newUrl);
// Setting socketUrl to null would also disconnect
}, []);
return (
Status: {ReadyState[readyState]}
{!shouldConnect && ' (Disconnected by user)'}
Authentication
{!isAuthenticated ? (
) : (
)}
Connection Control
Server Selection
{lastMessage && (
Last Message: {lastMessage.data}
)}
);
};
```
--------------------------------
### Reset Global WebSocket State with react-use-websocket
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
This example demonstrates how to reset the global WebSocket state using `resetGlobalState` from `react-use-websocket`. It shows usage within parent and child window components to manage shared WebSocket connections, particularly during window unload events. The function can be called with a specific URL to reset a single connection or without arguments to reset all shared connections.
```javascript
import React, { useEffect } from 'react';
import useWebSocket from 'react-use-websocket';
import { resetGlobalState } from 'react-use-websocket';
// Parent window component
export const ParentWindow = () => {
const socketUrl = 'wss://api.example.com/stream';
const { lastMessage, readyState } = useWebSocket(socketUrl, {
share: true
});
const openChildWindow = () => {
const childWindow = window.open('/child', 'ChildWindow', 'width=600,height=400');
// Store reference for cleanup
if (childWindow) {
window.childWindowRef = childWindow;
}
};
useEffect(() => {
// Cleanup when parent window closes
return () => {
// Reset state for specific URL
resetGlobalState(socketUrl);
};
}, [socketUrl]);
return (
Parent Window
Connection Status: {readyState}
Last Message: {lastMessage?.data}
);
};
// Child window component
export const ChildWindow = () => {
const socketUrl = 'wss://api.example.com/stream';
const { lastMessage, sendMessage, readyState } = useWebSocket(socketUrl, {
share: true // Shares WebSocket with parent
});
useEffect(() => {
// Critical: Reset global state when child window closes
const handleUnload = () => {
// Reset state for this specific connection
resetGlobalState(socketUrl);
// Or reset all connections:
// resetGlobalState();
};
window.addEventListener('beforeunload', handleUnload);
return () => {
window.removeEventListener('beforeunload', handleUnload);
handleUnload();
};
}, [socketUrl]);
return (
Child Window
Connection Status: {readyState}
Last Message: {lastMessage?.data}
);
};
```
--------------------------------
### Reset Global WebSocket State in Child Windows
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
This example shows how to reset the global state of the `react-use-websocket` library when a child window is closed. It uses a `useEffect` hook to add an `unload` event listener that calls `resetGlobalState` with the specific WebSocket URL. This prevents state conflicts in the main window when dynamically opened windows are closed.
```javascript
import React, { useEffect } from 'react';
import { resetGlobalState } from 'react-use-websocket';
// insside second window opened via window.open
export const ChildWindow = () => {
useEffect(() => {
window.addEventListener('unload', () => {
resetGlobalState('wss://echo.websocket.org');
});
}, []);
};
```
--------------------------------
### Basic Usage of useWebSocket Hook
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Demonstrates how to use the `useWebSocket` hook in a functional React component. It shows how to connect to a WebSocket server, send messages, and access connection status and received messages. It highlights options like `onOpen` and `shouldReconnect`.
```javascript
import useWebSocket from 'react-use-websocket';
// In functional React component
// This can also be an async getter function. See notes below on Async Urls.
const socketUrl = 'wss://echo.websocket.org';
const {
sendMessage,
sendJsonMessage,
lastMessage,
lastJsonMessage,
readyState,
getWebSocket
} = useWebSocket(socketUrl, {
onOpen: () => console.log('opened'),
//Will attempt to reconnect on all close events, such as server shutting down
shouldReconnect: (closeEvent) => true,
});
```
--------------------------------
### Basic WebSocket Connection Management with useWebSocket Hook
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
Demonstrates the primary useWebSocket hook for establishing and managing a basic WebSocket connection. It includes configuration for connection events, automatic reconnection attempts and intervals, and handles incoming messages for display. The hook simplifies real-time data flow and connection state management within a React component.
```javascript
import React, { useState, useCallback, useEffect } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const ChatComponent = () => {
const [socketUrl] = useState('wss://echo.websocket.org');
const [messageHistory, setMessageHistory] = useState([]);
const [inputValue, setInputValue] = useState('');
const {
sendMessage,
lastMessage,
readyState
} = useWebSocket(socketUrl, {
onOpen: () => console.log('WebSocket connected'),
onClose: () => console.log('WebSocket disconnected'),
onError: (event) => console.error('WebSocket error:', event),
shouldReconnect: (closeEvent) => true,
reconnectAttempts: 10,
reconnectInterval: 3000
});
useEffect(() => {
if (lastMessage !== null) {
setMessageHistory((prev) => [...prev, lastMessage.data]);
}
}, [lastMessage]);
const handleSendMessage = useCallback(() => {
if (inputValue.trim()) {
sendMessage(inputValue);
setInputValue('');
}
}, [inputValue, sendMessage]);
const connectionStatus = {
[ReadyState.CONNECTING]: 'Connecting',
[ReadyState.OPEN]: 'Open',
[ReadyState.CLOSING]: 'Closing',
[ReadyState.CLOSED]: 'Closed',
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
}[readyState];
return (
);
};
```
--------------------------------
### Direct WebSocket Access with getWebSocket in React
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
Demonstrates how to obtain direct access to the WebSocket instance using `getWebSocket` when `share` is set to `false`. This allows for advanced operations like modifying `binaryType`, checking `bufferedAmount`, and accessing properties like `url` and `extensions`. It requires the WebSocket to be open.
```javascript
import React, { useEffect, useCallback } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const DirectWebSocketAccess = () => {
const {
sendMessage,
lastMessage,
readyState,
getWebSocket
} = useWebSocket('wss://echo.websocket.org', {
share: false // Non-shared WebSocket allows direct access
});
useEffect(() => {
if (readyState === ReadyState.OPEN) {
const ws = getWebSocket();
if (ws) {
// Access WebSocket properties
console.log('Binary type:', ws.binaryType);
console.log('Buffered amount:', ws.bufferedAmount);
console.log('Extensions:', ws.extensions);
console.log('Protocol:', ws.protocol);
console.log('URL:', ws.url);
// Change binary type for binary data
ws.binaryType = 'arraybuffer';
// Check buffered data before sending large payloads
if (ws.bufferedAmount === 0) {
console.log('No buffered data, safe to send');
}
}
}
}, [readyState, getWebSocket]);
const sendBinaryData = useCallback(() => {
const ws = getWebSocket();
if (ws && readyState === ReadyState.OPEN) {
// Send ArrayBuffer
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setInt32(0, 42);
ws.send(buffer);
// Send Blob
const blob = new Blob(['Hello binary world'], { type: 'text/plain' });
ws.send(blob);
}
}, [getWebSocket, readyState]);
return (
Status: {ReadyState[readyState]}
);
};
```
--------------------------------
### Using useSocketIO Hook for Socket.IO Compatibility
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Shows how to import and use the `useSocketIO` hook for seamless integration with Socket.IO servers. This hook adapts the message handling to accommodate Socket.IO's specific message format.
```javascript
import { useSocketIO } from 'react-use-websocket';
// Same API in component
const { sendMessage, lastMessage, readyState } = useSocketIO(
'http://localhost:3000/'
);
// Note: lastMessage will be an object { type: string, payload: any } for Socket.IO
```
--------------------------------
### Other Returned Properties
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Details on `lastMessage`, `lastJsonMessage`, `readyState`, and `getWebSocket` returned by the `useWebSocket` hook.
```APIDOC
## Other Returned Properties
### Description
Provides details on the properties returned by the `useWebSocket` hook for inspecting the WebSocket's state and received messages.
### Properties
#### `lastMessage`
- **Type**: `WebSocketEventMap['message'] | null`
- **Description**: Contains the last message received from the server. It's `null` before the first message is received.
#### `lastJsonMessage`
- **Type**: `T | null`
- **Description**: Contains the last message received from the server, automatically parsed as JSON. If the message data is not valid JSON, this will be an empty object. It's `null` before the first JSON message is received.
#### `readyState`
- **Type**: `number`
- **Description**: Represents the current state of the WebSocket connection. Follows the standard WebSocket readyState mapping:
- `0`: Connecting
- `1`: OPEN
- `2`: CLOSING
- `3`: CLOSED
- `-1`: Uninstantiated
#### `getWebSocket`
- **Type**: `() => (WebSocketLike | null)`
- **Description**: Returns the underlying WebSocket instance or a proxy if the WebSocket is shared. Returns `null` if the WebSocket has not been instantiated.
### Example Usage
```javascript
const { lastMessage, lastJsonMessage, readyState, getWebSocket } = useWebSocket('wss://echo.websocket.org');
if (readyState === 1) {
console.log('WebSocket is open.');
}
if (lastMessage) {
console.log('Last message received:', lastMessage.data);
}
if (lastJsonMessage) {
console.log('Last JSON message received:', lastJsonMessage);
}
```
```
--------------------------------
### Use EventSource Hook for Server-Sent Events
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
This code illustrates the use of the `useEventSource` hook from `react-use-websocket`. It initializes an EventSource connection to a specified URL, with options for credentials and custom event handling. The hook provides `lastEvent`, `getEventSource`, and `readyState` for managing server-sent events.
```javascript
import { useEventSource } from 'react-use-websocket';
//Only the following three properties are provided
const { lastEvent, getEventSource, readyState } = useEventSource(
'http://localhost:3000/',
{
withCredentials: true,
events: {
message: (messageEvent) => {
console.log('This has type "message": ', messageEvent);
},
update: (messageEvent) => {
console.log('This has type "update": ', messageEvent);
},
},
}
);
```
--------------------------------
### Using Async URL with useWebSocket Hook
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Illustrates how to provide an asynchronous function that returns the WebSocket URL to the `useWebSocket` hook. This enables dynamic URL resolution, potentially fetching the URL from an API or based on component state. It uses `useCallback` to memoize the URL getter function.
```javascript
import useWebSocket from 'react-use-websocket';
// In functional React component
const getSocketUrl = useCallback(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('wss://echo.websocket.org');
}, 2000);
});
}, []);
const { sendMessage, lastMessage, readyState, getWebSocket } = useWebSocket(
getSocketUrl,
STATIC_OPTIONS
);
```
--------------------------------
### Manage WebSocket Message Queuing with react-use-websocket
Source: https://context7.com/robtaussig/react-use-websocket/llms.txt
This component demonstrates sending messages with and without queueing using the `react-use-websocket` library. It allows users to send text and JSON messages, with options to control whether messages are queued if the connection is not open. Received messages are displayed, along with the connection status and the count of queued messages.
```javascript
import React, { useState, useCallback, useEffect } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
export const MessageQueueComponent = () => {
const [queuedMessages, setQueuedMessages] = useState(0);
const [sentMessages, setSentMessages] = useState([]);
const {
sendMessage,
sendJsonMessage,
readyState,
lastMessage
} = useWebSocket('wss://echo.websocket.org', {
shouldReconnect: () => true,
reconnectInterval: 3000,
onOpen: () => {
console.log('Connected - queued messages will be sent now');
setQueuedMessages(0);
}
});
// Send message with queueing (default behavior)
const sendQueuedMessage = useCallback((text) => {
// keep=true (default): message is queued if connection not open
sendMessage(text, true);
if (readyState !== ReadyState.OPEN) {
setQueuedMessages(prev => prev + 1);
console.log('Message queued, will send when connected');
} else {
setSentMessages(prev => [...prev, text]);
}
}, [sendMessage, readyState]);
// Send message without queueing
const sendImmediateMessage = useCallback((text) => {
// keep=false: message is dropped if connection not open
sendMessage(text, false);
if (readyState === ReadyState.OPEN) {
setSentMessages(prev => [...prev, text]);
console.log('Message sent immediately');
} else {
console.log('Message dropped - connection not open');
}
}, [sendMessage, readyState]);
// Send JSON with queue control
const sendQueuedJson = useCallback((data, useQueue = true) => {
sendJsonMessage(data, useQueue);
if (readyState !== ReadyState.OPEN && useQueue) {
setQueuedMessages(prev => prev + 1);
}
}, [sendJsonMessage, readyState]);
// Example: Send critical messages that should be queued
const sendCriticalUpdate = useCallback(() => {
sendQueuedMessage('CRITICAL: User action logged');
sendQueuedJson({
type: 'USER_ACTION',
action: 'PURCHASE',
timestamp: Date.now()
}, true); // Always queue critical messages
}, [sendQueuedMessage, sendQueuedJson]);
// Example: Send ephemeral messages that shouldn't be queued
const sendHeartbeat = useCallback(() => {
sendImmediateMessage('ping');
// Or with JSON
sendJsonMessage({ type: 'HEARTBEAT' }, false); // Don't queue heartbeats
}, [sendImmediateMessage, sendJsonMessage]);
useEffect(() => {
// Demonstrate queuing on component mount (before connection)
if (readyState === ReadyState.CONNECTING) {
sendQueuedMessage('Early message 1');
sendQueuedMessage('Early message 2');
sendQueuedMessage('Early message 3');
}
}, [readyState, sendQueuedMessage]);
return (
Status: {ReadyState[readyState]}
Queued Messages: {queuedMessages}
Sent Messages:
{sentMessages.map((msg, idx) => (
{msg}
))}
{lastMessage && (
Last Echo: {lastMessage.data}
)}
);
};
```
--------------------------------
### Appending Query Parameters to WebSocket URL
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Demonstrates how to append custom query parameters to the WebSocket connection URL using the `queryParams` option. These parameters are stringified and added to the URL, allowing for server-side identification or configuration.
```javascript
const queryParams = {
user_id: 1,
room_id: 5,
};
// The URL will become: ?user_id=1&room_id=5
```
--------------------------------
### useWebSocket Hook
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
The primary hook for establishing and managing WebSocket connections. It accepts a URL and an options object to configure connection behavior, event handlers, and reconnection logic.
```APIDOC
## `useWebSocket` Hook
### Description
Provides a hook to manage WebSocket connections within functional React components. It handles connection, disconnection, message sending/receiving, and reconnection.
### Method
`useWebSocket(url, options?, shouldConnect?)
### Parameters
#### url
- **url** (`string | () => Promise`) - Required - The WebSocket server URL or an async function returning the URL.
#### options
- **fromSocketIO** (`boolean`) - Optional - Set to true for Socket.IO support.
- **queryParams** (`{ [field: string]: any }`) - Optional - Query parameters to append to the URL.
- **protocols** (`string | string[]`) - Optional - WebSocket subprotocols.
- **share** (`boolean`) - Optional - If true, allows multiple components to share a single WebSocket instance.
- **onOpen** (`(event: WebSocketEventMap['open']) => void`) - Optional - Callback function when the connection opens.
- **onClose** (`(event: WebSocketEventMap['close']) => void`) - Optional - Callback function when the connection closes.
- **onMessage** (`(event: WebSocketEventMap['message']) => void`) - Optional - Callback function when a message is received.
- **onError** (`(event: WebSocketEventMap['error']) => void`) - Optional - Callback function when an error occurs.
- **onReconnectStop** (`(numAttempts: number) => void`) - Optional - Callback function when reconnection attempts stop.
- **shouldReconnect** (`(event: WebSocketEventMap['close']) => boolean`) - Optional - Function to determine if reconnection should occur.
- **reconnectInterval** (`number | ((lastAttemptNumber: number) => number)`) - Optional - Interval between reconnection attempts.
- **reconnectAttempts** (`number`) - Optional - Maximum number of reconnection attempts.
- **filter** (`(message: WebSocketEventMap['message']) => boolean`) - Optional - Function to filter incoming messages.
- **disableJson** (`boolean`) - Optional - If true, disables automatic JSON parsing.
- **retryOnError** (`boolean`) - Optional - If true, retries connection on error.
- **eventSourceOptions** (`EventSourceInit`) - Optional - Options for EventSource API.
- **heartbeat** (`boolean | { message?: "ping" | "pong" | string | (() => string); returnMessage?: "ping" | "pong" | string; timeout?: number; interval?: number; }`) - Optional - Configuration for heartbeat messages.
#### shouldConnect
- **shouldConnect** (`boolean`) - Optional - If false, the WebSocket connection will not be established initially.
### Returns
An object containing:
- **sendMessage**: Function to send messages.
- **sendJsonMessage**: Function to send JSON messages.
- **lastMessage**: The last received message.
- **lastJsonMessage**: The last received JSON message.
- **readyState**: The current ready state of the WebSocket connection.
- **getWebSocket**: Function to get the underlying WebSocket instance.
### Request Example
```javascript
import useWebSocket from 'react-use-websocket';
const socketUrl = 'wss://echo.websocket.org';
const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl, {
shouldReconnect: (closeEvent) => true,
});
```
### Response Example
```json
{
"lastMessage": "Hello World!",
"readyState": 1 // OPEN
}
```
```
--------------------------------
### sendMessage Function
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Function to send string messages over the WebSocket connection. Messages sent before connection are queued.
```APIDOC
## `sendMessage` Function
### Description
Sends a string message through the WebSocket connection. If the connection is not yet open, the message will be queued and sent once the connection is established. The `keep` parameter can be used to prevent queuing for specific messages.
### Method
`sendMessage(message: string, keep: boolean = true)`
### Parameters
#### message
- **message** (`string`) - Required - The message to send.
#### keep
- **keep** (`boolean`) - Optional (default: `true`) - If `false`, the message will not be queued if the WebSocket is not open.
### Request Example
```javascript
// Assuming sendMessage is obtained from useWebSocket hook
sendMessage('Hello WebSocket!');
```
```
--------------------------------
### useWebSocket Hook Interface Definition
Source: https://github.com/robtaussig/react-use-websocket/blob/master/README.md
Provides the TypeScript type definition for the `useWebSocket` hook, outlining its parameters, options, and return values. This is useful for understanding the full range of customization available for WebSocket connections.
```typescript
type UseWebSocket = (
//Url can be return value of a memoized async function.
url: string | () => Promise,
options: {
fromSocketIO?: boolean;
queryParams?: { [field: string]: any };
protocols?: string | string[];
share?: boolean;
onOpen?: (event: WebSocketEventMap['open']) => void;
onClose?: (event: WebSocketEventMap['close']) => void;
onMessage?: (event: WebSocketEventMap['message']) => void;
onError?: (event: WebSocketEventMap['error']) => void;
onReconnectStop?: (numAttempts: number) => void;
shouldReconnect?: (event: WebSocketEventMap['close']) => boolean;
reconnectInterval?: number | ((lastAttemptNumber: number) => number);
reconnectAttempts?: number;
filter?: (message: WebSocketEventMap['message']) => boolean;
disableJson?: boolean;
retryOnError?: boolean;
eventSourceOptions?: EventSourceInit;
heartbeat?: boolean | {
message?: "ping" | "pong" | string | (() => string);
returnMessage?: "ping" | "pong" | string;
timeout?: number;
interval?: number;
};
} = {},
shouldConnect: boolean = true,
): {
sendMessage: (message: string, keep: boolean = true) => void,
//jsonMessage must be JSON-parsable
sendJsonMessage: (jsonMessage: T, keep: boolean = true) => void,
//null before first received message
lastMessage: WebSocketEventMap['message'] | null,
//null before first received message. If message.data is not JSON parsable, then this will be a static empty object
lastJsonMessage: T | null,
// -1 if uninstantiated, otherwise follows WebSocket readyState mapping: 0: 'Connecting', 1 'OPEN', 2: 'CLOSING', 3: 'CLOSED'
readyState: number,
// If using a shared websocket, return value will be a proxy-wrapped websocket, with certain properties/methods protected
getWebSocket: () => (WebSocketLike | null),
}
```