);
};
```
--------------------------------
### SocketIO Message Format
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=versions
Example of the non-JSON-parsable message format used by SocketIO.
```text
"42["Action",{"key":"value"}]"
```
--------------------------------
### Configure reconnection logic
Source: https://www.npmjs.com/package/react-use-websocket
Example of using shouldReconnect to conditionally manage reconnection attempts based on component lifecycle.
```javascript
const didUnmount = useRef(false);
const [sendMessage, lastMessage, readyState] = useWebSocket(
'wss://echo.websocket.org',
{
shouldReconnect: (closeEvent) => {
/*
useWebSocket will handle unmounting for you, but this is an example of a
case in which you would not want it to automatically reconnect
*/
return didUnmount.current === false;
},
reconnectAttempts: 10,
reconnectInterval: 3000,
}
);
useEffect(() => {
return () => {
didUnmount.current = true;
};
}, []);
```
--------------------------------
### Filter Incoming Messages
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=versions
Example of using the filter callback to conditionally process messages and prevent unnecessary component re-renders.
```javascript
filter: (message) => {
// validate your message data
if (isPingMessage(message.data)) {
// do stuff or simply return false
updateHeartbeat()
return false
} else {
return true
}
},
```
--------------------------------
### Filtering Incoming WebSocket Messages
Source: https://www.npmjs.com/package/react-use-websocket
Provides an example of using the `filter` option to conditionally process incoming WebSocket messages. Only messages for which the filter function returns `true` will update the component's state.
```javascript
filter: (message) => {
// validate your message data
if (isPingMessage(message.data)) {
// do stuff or simply return false
updateHeartbeat()
return false
} else {
return true
}
},
```
--------------------------------
### Reset Global State for WebSocket Connections
Source: https://www.npmjs.com/package/react-use-websocket
Provides a method to reset the global state of the react-use-websocket library, which is useful in scenarios involving multiple windows or if the library's state does not reset automatically. This example shows how to call `resetGlobalState` when a child window is unloaded.
```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');
});
}, []);
};
```
--------------------------------
### Socket.IO Compatibility
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependents
Enable experimental support for Socket.IO connections.
```APIDOC
## Socket.IO Compatibility
### fromSocketIO
**Description**: This experimental option enables compatibility with Socket.IO. Socket.IO uses a layer on top of the WebSocket protocol with specific message formats. Setting `fromSocketIO` to `true` attempts to handle these formats, potentially allowing `useWebSocket` to work interchangeably with Socket.IO back-ends.
**Note**: This feature is experimental and relies on the stability of the Socket.IO client library API. Tested with Socket.IO `2.1.1`.
**Usage**: Set the `fromSocketIO` property to `true` in the options object.
```javascript
const { sendMessage, lastMessage, readyState } = useWebSocket('http://localhost:3000/', {
fromSocketIO: true,
});
```
### useSocketIO Hook
**Description**: An alternative hook `useSocketIO` is available for direct use with Socket.IO. It provides the same API but handles Socket.IO's message structure.
**Usage**: Import and use `useSocketIO` instead of `useWebSocket` for Socket.IO specific scenarios.
```javascript
import { useSocketIO } from 'react-use-websocket';
const { sendMessage, lastMessage, readyState } = useSocketIO('http://localhost:3000/');
```
**`lastMessage` Format**: When using `useSocketIO`, `lastMessage` will be an object with `type` and `payload` keys, rather than a raw `MessageEvent`.
```
--------------------------------
### react-use-websocket Options
Source: https://www.npmjs.com/package/react-use-websocket
Configuration options for the useWebSocket hook.
```APIDOC
## Options Interface
```typescript
interface Options {
share?: boolean;
shouldReconnect?: (event: WebSocketEventMap['close']) => boolean;
reconnectInterval?: number | ((lastAttemptNumber: number) => number);
reconnectAttempts?: number;
filter?: (message: WebSocketEventMap['message']) => boolean;
disableJson?: boolean;
retryOnError?: boolean;
onOpen?: (event: WebSocketEventMap['open']) => void;
onClose?: (event: WebSocketEventMap['close']) => void;
onMessage?: (event: WebSocketEventMap['message']) => void;
onError?: (event: WebSocketEventMap['error']) => void;
onReconnectStop?: (numAttempted: number) => void;
fromSocketIO?: boolean;
queryParams?: {
[key: string]: string | number;
};
protocols?: string | string[];
eventSourceOptions?: EventSourceInit;
heartbeat?:
| boolean
| {
message?: 'ping' | 'pong' | string;
returnMessage?: 'ping' | 'pong' | string;
timeout?: number;
interval?: number;
};
}
```
### `share` (Boolean)
If set to `true`, a new WebSocket will not be instantiated if one for the same url has already been created for another component. Once all subscribing components have either unmounted or changed their target socket url, shared WebSockets will be closed and cleaned up.
### `shouldReconnect` (Callback)
Determines if a reconnection should be attempted based on the WebSocket close event. See section on Reconnecting for more details.
### `reconnectInterval` (Number | Callback)
Number of milliseconds to wait until it attempts to reconnect. Default is 5000. Can also be defined as a function that takes the last attemptCount and returns the amount of time for the next interval. See Reconnecting for an example.
### `reconnectAttempts` (Number)
The maximum number of reconnection attempts.
### `filter` (Callback)
If a function is provided, incoming messages will be passed through this function. Only if it returns `true` will the hook pass along the `lastMessage` and update the component. This is useful for ignoring specific messages, like ping/pong frames, to prevent unnecessary re-renders.
Example:
```javascript
filter: (message) => {
if (isPingMessage(message.data)) {
updateHeartbeat();
return false;
} else {
return true;
}
},
```
### `disableJson` (Boolean)
If set to `true`, messages will not be automatically parsed as JSON.
### `retryOnError` (Boolean)
If set to `true`, the hook will attempt to reconnect when an error occurs.
### Event Handlers: Callback
Each of `onOpen`, `onClose`, `onMessage`, and `onError` will be called on the corresponding WebSocket event, if provided. Each will be passed the same event provided from the WebSocket.
- **`onOpen`**: Called when the WebSocket connection is opened.
- **`onClose`**: Called when the WebSocket connection is closed.
- **`onMessage`**: Called when a message is received from the WebSocket.
- **`onError`**: Called when an error occurs with the WebSocket connection.
### `onReconnectStop` (Callback)
If provided, this callback will be called when the WebSocket exceeds the reconnect limit (either the one provided in options or the default value of 20).
### `fromSocketIO` (Boolean)
If set to `true`, the hook will attempt to handle messages in the Socket.IO format. This is an experimental option and was tested with Socket IO `2.1.1`.
### `queryParams` (Object)
Pass an object representing query parameters, which will be converted into stringified query parameters and appended to the WebSocket URL.
Example:
```javascript
const queryParams = {
user_id: 1,
room_id: 5,
};
// Appended to URL: ?user_id=1&room_id=5
```
### `protocols` (String | String[])
Specify the sub-protocols to be used for the WebSocket connection.
### `eventSourceOptions` (EventSourceInit)
Options to be passed to the underlying EventSource constructor, if used.
### `heartbeat` (Boolean | Object)
If set to `true` or an object with options, the library will send a 'ping' message to the server periodically. If no response is received within the `timeout` period, the connection will be closed. You can customize the message, return message, timeout, and interval.
Example:
```javascript
const { sendMessage, lastMessage, readyState } = useWebSocket(
'ws://localhost:3000',
{
heartbeat: {
message: 'ping',
returnMessage: 'pong',
timeout: 60000, // 1 minute
interval: 25000, // every 25 seconds
},
}
);
```
```
--------------------------------
### react-use-websocket Options
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=readme
Configuration options for the useWebSocket hook.
```APIDOC
## Options
### `share` (Boolean)
If set to `true`, a new WebSocket will not be instantiated if one for the same url has already been created for another component. Once all subscribing components have either unmounted or changed their target socket url, shared WebSockets will be closed and cleaned up.
### `shouldReconnect` (Function)
Determines if the WebSocket should attempt to reconnect. Receives the WebSocket close event.
### `reconnectInterval` (Number | Function)
Number of milliseconds to wait until it attempts to reconnect. Default is 5000. Can also be defined as a function that takes the last attemptCount and returns the amount of time for the next interval.
### `reconnectAttempts` (Number)
Maximum number of reconnection attempts.
### `filter` (Function)
If a function is provided, incoming messages will be passed through it. Only if it returns `true` will the hook pass along the `lastMessage` and update the component. This is useful for filtering out specific message types, like heartbeat pings.
### `disableJson` (Boolean)
If set to `true`, messages will not be automatically parsed as JSON.
### `retryOnError` (Boolean)
If set to `true`, the WebSocket will attempt to reconnect on encountering an error.
### Event Handlers (`onOpen`, `onClose`, `onMessage`, `onError`)
Callback functions that are executed when the corresponding WebSocket event occurs. Each will be passed the same event provided from the WebSocket.
- `onOpen`: Called when the WebSocket connection is opened.
- `onClose`: Called when the WebSocket connection is closed.
- `onMessage`: Called when a message is received from the WebSocket.
- `onError`: Called when an error occurs with the WebSocket connection.
### `onReconnectStop` (Function)
If provided, this callback will be called when the WebSocket exceeds the maximum reconnect limit.
### `fromSocketIO` (Boolean)
If set to `true`, the hook will attempt to handle messages in the Socket.IO format. This is an experimental option.
### `queryParams` (Object)
An object representing query parameters to be appended to the WebSocket URL. Keys and values will be stringified.
```javascript
const queryParams = {
user_id: 1,
room_id: 5,
};
// Appended to URL as: ?user_id=1&room_id=5
```
### `protocols` (String | Array)
Specifies the sub-protocols to be offered by the client when establishing a connection.
### `eventSourceOptions` (Object)
Options to be passed to the underlying EventSource constructor, if used.
### `heartbeat` (Boolean | Object)
If set to `true` or an object with options, the library will send a heartbeat message to the server.
- `message` (String): The message to send as a heartbeat (default: 'ping').
- `returnMessage` (String): A message that, if received, will be ignored and not set as `lastMessage`.
- `timeout` (Number): Time in milliseconds to wait for a heartbeat response before closing the connection (default: 60000).
- `interval` (Number): Time in milliseconds between sending heartbeat messages (default: 25000).
```javascript
const { sendMessage, lastMessage, readyState } = useWebSocket(
'ws://localhost:3000',
{
heartbeat: {
message: 'ping',
returnMessage: 'pong',
timeout: 60000,
interval: 25000,
},
}
);
```
```
--------------------------------
### Initialize useEventSource Hook
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=readme
Instantiates an EventSource connection with specific event listeners and configuration options.
```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);
},
},
}
);
```
--------------------------------
### Options Interface
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependents
The Options interface defines all configurable parameters for the useWebSocket hook.
```APIDOC
## Options Interface
### Description
Defines the structure for configuration options passed to the `useWebSocket` hook.
### Parameters
#### Request Body
- **share** (boolean) - Optional - If true, shares an existing WebSocket connection for the same URL.
- **shouldReconnect** (function) - Optional - A callback function to determine if a reconnection should be attempted based on the close event.
- **reconnectInterval** (number | function) - Optional - The interval in milliseconds (or a function returning milliseconds) to wait before attempting to reconnect. Defaults to 5000ms.
- **reconnectAttempts** (number) - Optional - The maximum number of reconnection attempts. Defaults to 20.
- **filter** (function) - Optional - A callback function that filters incoming messages. Only messages for which this function returns `true` will be processed.
- **disableJson** (boolean) - Optional - If true, disables automatic JSON parsing of messages.
- **retryOnError** (boolean) - Optional - If true, attempts to reconnect on encountering an error.
- **onOpen** (function) - Optional - Callback function executed when the WebSocket connection is opened.
- **onClose** (function) - Optional - Callback function executed when the WebSocket connection is closed.
- **onMessage** (function) - Optional - Callback function executed when a message is received.
- **onError** (function) - Optional - Callback function executed when a WebSocket error occurs.
- **onReconnectStop** (function) - Optional - Callback function executed when reconnection attempts are exhausted.
- **fromSocketIO** (boolean) - Optional - If true, enables experimental support for Socket.IO compatible messages.
- **queryParams** (object) - Optional - An object of key-value pairs to be appended as query parameters to the WebSocket URL.
- **protocols** (string | string[]) - Optional - A string or array of strings specifying the sub-protocols to use.
- **eventSourceOptions** (EventSourceInit) - Optional - Options for the underlying EventSource if used.
- **heartbeat** (boolean | object) - Optional - Enables and configures heartbeat messages for connection health checks.
- **message** (string) - The message to send as a heartbeat (default: 'ping').
- **returnMessage** (string) - Expected response message for the heartbeat (ignored for `lastMessage`).
- **timeout** (number) - Time in milliseconds to wait for a heartbeat response before closing the connection.
- **interval** (number) - Interval in milliseconds between sending heartbeat messages.
```
--------------------------------
### useWebSocket State Variables
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependencies
Explains the state variables provided by the useWebSocket hook.
```APIDOC
## lastMessage
### Description
Will be an unparsed `MessageEvent` received from the WebSocket.
### Type
```typescript
type lastMessage = WebSocketEventMap['message'];
```
## lastJsonMessage
### Description
A `JSON.parse`d object from the `lastMessage`. If `lastMessage` is not a valid JSON string, `lastJsonMessage` will be an empty object. If `Options#disableJson` is `true`, `lastMessage` will not be automatically parsed, and `lastJsonMessage` will always be `null`.
### Type
```typescript
type lastJsonMessage = any;
```
## readyState
### Description
Will be an integer representing the `readyState` of the WebSocket. `-1` is not a valid WebSocket `readyState`, but instead indicates that the WebSocket has not been instantiated yet (either because the url is `null` or connect param is `false`).
### Enum
```typescript
enum ReadyState {
UNINSTANTIATED = -1,
CONNECTING = 0,
OPEN = 1,
CLOSING = 2,
CLOSED = 3,
}
```
```
--------------------------------
### useWebSocket Options Configuration
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=versions
Configuration options for the useWebSocket hook to manage connection behavior, event callbacks, and message processing.
```APIDOC
## useWebSocket Options
### Description
Configuration object passed to the useWebSocket hook to control connection lifecycle, reconnection logic, and event handling.
### Parameters
#### Request Body
- **share** (boolean) - Optional - If true, shares the WebSocket instance across components.
- **shouldReconnect** (function) - Optional - Callback to determine if the socket should attempt to reconnect.
- **reconnectInterval** (number | function) - Optional - Milliseconds to wait before reconnecting. Default is 5000.
- **reconnectAttempts** (number) - Optional - Maximum number of reconnection attempts.
- **filter** (function) - Optional - Callback to filter incoming messages.
- **disableJson** (boolean) - Optional - If true, disables automatic JSON parsing.
- **retryOnError** (boolean) - Optional - If true, attempts to reconnect on error.
- **onOpen** (function) - Optional - Callback triggered on WebSocket open event.
- **onClose** (function) - Optional - Callback triggered on WebSocket close event.
- **onMessage** (function) - Optional - Callback triggered on WebSocket message event.
- **onError** (function) - Optional - Callback triggered on WebSocket error event.
- **onReconnectStop** (function) - Optional - Callback triggered when reconnection limit is reached.
- **fromSocketIO** (boolean) - Optional - Enables compatibility mode for SocketIO backends.
- **queryParams** (object) - Optional - Key-value pairs appended as query strings to the URL.
- **protocols** (string | string[]) - Optional - WebSocket sub-protocols.
- **heartbeat** (boolean | object) - Optional - Configuration for automated heartbeat/ping-pong messages.
```
--------------------------------
### Reconnection Configuration
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=readme
How to configure automatic reconnection strategies using the useWebSocket options.
```APIDOC
## Reconnection Configuration
### Options
- **retryOnError** (boolean) - If `true`, attempts to reconnect on error events.
- **shouldReconnect** (function) - Callback receiving `CloseEvent`. Return `true` to trigger reconnection.
- **reconnectAttempts** (number) - Maximum number of reconnection attempts (default: 20).
- **reconnectInterval** (number | function) - Delay in ms between attempts, or a function returning the delay based on attempt count.
```
--------------------------------
### Initialize useWebSocket Hook
Source: https://www.npmjs.com/package/react-use-websocket
Basic usage of the useWebSocket hook within a functional React component.
```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,
});
```
--------------------------------
### Configuring Heartbeat for WebSocket Connections
Source: https://www.npmjs.com/package/react-use-websocket
Illustrates how to enable and configure the heartbeat feature for maintaining WebSocket connections. This includes setting custom messages, response messages, timeouts, and intervals.
```javascript
const { sendMessage, lastMessage, readyState } = useWebSocket(
'ws://localhost:3000',
{
heartbeat: {
message: 'ping',
returnMessage: 'pong',
timeout: 60000, // 1 minute, if no response is received, the connection will be closed
interval: 25000, // every 25 seconds, a ping message will be sent
},
}
);
```
--------------------------------
### Using useSocketIO Hook for Socket.IO Compatibility
Source: https://www.npmjs.com/package/react-use-websocket
Shows how to import and use the `useSocketIO` hook for compatibility with Socket.IO back-ends. Note that `lastMessage` will be an object with `type` and `payload` keys, not a `MessageEvent`.
```javascript
import { useSocketIO } from 'react-use-websocket';
//Same API in component
const { sendMessage, lastMessage, readyState } = useSocketIO(
'http://localhost:3000/'
);
```
--------------------------------
### Interact with shared WebSocket via getWebSocket
Source: https://www.npmjs.com/package/react-use-websocket
Demonstrates how to access and modify properties of a shared WebSocket instance using the getWebSocket function.
```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.'
}, []);
```
--------------------------------
### useSocketIO Hook
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=versions
An extension of the useWebSocket hook specifically designed for SocketIO compatibility.
```APIDOC
## useSocketIO
### Description
An extension of the useWebSocket hook that handles the non-JSON-parsable message format used by SocketIO.
### Request Example
import { useSocketIO } from 'react-use-websocket';
const { sendMessage, lastMessage, readyState } = useSocketIO('http://localhost:3000/');
### Response
#### Success Response (200)
- **lastMessage** (object) - Returns an object with 'type' and 'payload' keys instead of a standard MessageEvent.
```
--------------------------------
### Use EventSource Hook in React
Source: https://www.npmjs.com/package/react-use-websocket
Demonstrates how to use the `useEventSource` hook to connect to an EventSource endpoint. It shows how to handle incoming messages with custom event listeners and access connection state.
```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);
},
},
}
);
```
--------------------------------
### Reconnection Configuration
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=code
How to configure automatic reconnection behavior using the useWebSocket options.
```APIDOC
## Reconnection Configuration
### Options
- **retryOnError** (boolean) - Optional - If `true`, attempts to reconnect on error events.
- **shouldReconnect** (function) - Optional - Callback receiving `CloseEvent`. Return `true` to trigger reconnection.
- **reconnectAttempts** (number) - Optional - Maximum number of reconnection attempts (default: 20).
- **reconnectInterval** (number | function) - Optional - Interval in ms between attempts, or a function returning the interval based on attempt count.
```
--------------------------------
### Event Handlers
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependents
Callbacks for handling WebSocket events.
```APIDOC
## Event Handlers
### Description
Provides callback functions that are executed when specific WebSocket events occur. These handlers receive the corresponding `Event` object from the WebSocket API.
### Available Handlers
- **onOpen**: Called when the WebSocket connection is successfully opened.
- **onClose**: Called when the WebSocket connection is closed.
- **onMessage**: Called when a message is received from the server.
- **onError**: Called when a WebSocket error occurs.
### Usage
Pass these functions within the `options` object when calling `useWebSocket`.
```javascript
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://localhost:8080', {
onOpen: (event) => {
console.log('WebSocket connection opened:', event);
},
onClose: (event) => {
console.log('WebSocket connection closed:', event);
},
onMessage: (event) => {
console.log('Message received:', event.data);
},
onError: (event) => {
console.error('WebSocket error:', event);
},
});
```
```
--------------------------------
### Share Connection
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependents
Configure the hook to share a single WebSocket instance across multiple components.
```APIDOC
## Share Connection
### share
**Description**: When set to `true`, this option ensures that if a WebSocket connection for the same URL already exists, a new one will not be created. Instead, the existing connection will be shared among all components using this option. The shared connection is automatically closed and cleaned up once all subscribing components have unmounted or changed their target URL.
**Usage**: Set the `share` property to `true` in the options object.
```javascript
const { sendMessage, lastMessage, readyState } = useWebSocket(url, {
share: true,
});
```
```
--------------------------------
### Reconnecting Options
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependents
Details on how to configure automatic reconnection behavior.
```APIDOC
## Reconnecting Options
### shouldReconnect
**Description**: Determines if a reconnection attempt should be made after the connection closes. This function receives the `CloseEvent` object.
**Usage**: Provide a function that returns `true` to attempt reconnection, `false` otherwise.
```javascript
shouldReconnect: (event) => {
// Example: Reconnect only if the close code is not a normal closure
return event.code !== 1000;
}
```
### reconnectInterval
**Description**: Specifies the delay between reconnection attempts. This can be a fixed number of milliseconds or a function that calculates the interval based on the number of attempts.
**Usage**: Provide a number for a fixed interval or a function `(lastAttemptNumber: number) => number` for dynamic intervals.
**Default**: 5000ms
```javascript
// Fixed interval
reconnectInterval: 10000,
// Dynamic interval (e.g., exponential backoff)
reconnectInterval: (attempt) => Math.pow(2, attempt) * 1000,
```
### reconnectAttempts
**Description**: Sets the maximum number of times the hook will attempt to reconnect.
**Default**: 20
**Usage**: Provide a number representing the maximum attempts.
```javascript
reconnectAttempts: 10,
```
### onReconnectStop
**Description**: A callback function that is invoked when the hook stops attempting to reconnect after exceeding the `reconnectAttempts` limit.
**Usage**: Provide a function that accepts the total number of attempted reconnections.
```javascript
onReconnectStop: (numAttempted) => {
console.log(`Reconnection stopped after ${numAttempted} attempts.`);
}
```
```
--------------------------------
### Define ReadyState enum
Source: https://www.npmjs.com/package/react-use-websocket
Integer constants representing the current connection status of the WebSocket.
```typescript
enum ReadyState {
UNINSTANTIATED = -1,
CONNECTING = 0,
OPEN = 1,
CLOSING = 2,
CLOSED = 3,
}
```
--------------------------------
### useSocketIO Hook
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=readme
An extension of the useWebSocket hook specifically for handling Socket.IO connections.
```APIDOC
## useSocketIO
Socket.IO sends messages in a format that isn't JSON-parsable. An extension of this hook is available by importing `useSocketIO`.
### Usage
```javascript
import { useSocketIO } from 'react-use-websocket';
// Same API in component
const { sendMessage, lastMessage, readyState } = useSocketIO(
'http://localhost:3000/'
);
```
### `lastMessage` Format
It is important to note that `lastMessage` will not be a `MessageEvent`, but instead an object with two keys: `type` and `payload`.
```
--------------------------------
### useSocketIO Hook
Source: https://www.npmjs.com/package/react-use-websocket
An extension of the useWebSocket hook specifically for handling Socket.IO connections.
```APIDOC
## `useSocketIO`
Socket.IO sends messages in a format that isn't JSON-parsable, such as `"42["Action",{"key":"value"}]"`.
An extension of the `useWebSocket` hook is available by importing `useSocketIO`:
```javascript
import { useSocketIO } from 'react-use-websocket';
// Same API in component
const { sendMessage, lastMessage, readyState } = useSocketIO(
'http://localhost:3000/'
);
```
It is important to note that `lastMessage` will not be a `MessageEvent`, but instead an object with two keys: `type` and `payload`.
```
--------------------------------
### Interface Options for react-use-websocket
Source: https://www.npmjs.com/package/react-use-websocket
Defines the structure for all available options when configuring the useWebSocket hook. This includes settings for reconnection, event callbacks, message filtering, and more.
```typescript
interface Options {
share?: boolean;
shouldReconnect?: (event: WebSocketEventMap['close']) => boolean;
reconnectInterval?: number | ((lastAttemptNumber: number) => number);
reconnectAttempts?: number;
filter?: (message: WebSocketEventMap['message']) => boolean;
disableJson?: boolean;
retryOnError?: boolean;
onOpen?: (event: WebSocketEventMap['open']) => void;
onClose?: (event: WebSocketEventMap['close']) => void;
onMessage?: (event: WebSocketEventMap['message']) => void;
onError?: (event: WebSocketEventMap['error']) => void;
onReconnectStop?: (numAttempted: number) => void;
fromSocketIO?: boolean;
queryParams?: {
[key: string]: string | number;
};
protocols?: string | string[];
eventSourceOptions?: EventSourceInit;
heartbeat?:
| boolean
| {
message?: 'ping' | 'pong' | string;
returnMessage?: 'ping' | 'pong' | string;
timeout?: number;
interval?: number;
};
}
```
--------------------------------
### Appending Query Parameters to WebSocket URL
Source: https://www.npmjs.com/package/react-use-websocket
Demonstrates how to define and append custom query parameters to the WebSocket URL using the `queryParams` option. These parameters are automatically stringified and added to the URL.
```javascript
const queryParams = {
user_id: 1,
room_id: 5,
};
//?user_id=1&room_id=5
```
--------------------------------
### Heartbeat Configuration
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependents
Configure heartbeat messages to maintain connection health.
```APIDOC
## Heartbeat Configuration
### heartbeat
**Description**: The `heartbeat` option allows you to configure automatic heartbeat messages to ensure the WebSocket connection remains active and to detect potential issues. If enabled, a 'ping' message is sent at a specified `interval`. If no response is received within the `timeout` period, the connection is closed.
**Usage**: Set `heartbeat` to `true` for default behavior, or provide an object with custom configuration.
**Options**:
- `message` (string): The message content to send as a heartbeat. Defaults to `'ping'`.
- `returnMessage` (string): The expected response message. This message will be ignored and not set as `lastMessage`.
- `timeout` (number): The time in milliseconds to wait for a heartbeat response before closing the connection. Defaults to 60000ms (1 minute).
- `interval` (number): The interval in milliseconds between sending heartbeat messages. Defaults to 25000ms (25 seconds).
**Example**:
```javascript
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://localhost:3000', {
heartbeat: {
message: 'ping',
returnMessage: 'pong', // This will be ignored for lastMessage
timeout: 60000, // 1 minute timeout
interval: 25000, // Send ping every 25 seconds
},
});
```
**Note**: If `heartbeat` is set to `true` without an object, default ping messages will be sent every 25 seconds, with a 1-minute timeout for responses.
```
--------------------------------
### Query Parameters
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependents
Append custom query parameters to the WebSocket URL.
```APIDOC
## Query Parameters
### queryParams
**Description**: The `queryParams` option allows you to pass an object containing key-value pairs that will be automatically stringified and appended as query parameters to the WebSocket connection URL.
**Usage**: Provide an object where keys are parameter names and values are their corresponding string or number values.
**Example**:
```javascript
const queryParams = {
user_id: 123,
session_token: 'abc-xyz',
room_id: 5,
};
const { sendMessage, lastMessage, readyState } = useWebSocket('ws://localhost:3000', {
queryParams: queryParams,
});
// The effective URL will be: 'ws://localhost:3000?user_id=123&session_token=abc-xyz&room_id=5'
```
```
--------------------------------
### useEventSource Hook
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=code
Instantiates an EventSource connection with support for custom event listeners and connection options.
```APIDOC
## useEventSource
### Description
Instantiates an EventSource instead of a WebSocket. It tracks readyStates (CONNECTING, OPEN, CLOSED) and provides access to the underlying EventSource instance.
### Parameters
#### Arguments
- **url** (string) - Required - The URL to connect to.
- **options** (object) - Optional - Configuration object including `withCredentials` and `events` map.
### Response
- **lastEvent** (MessageEvent) - The last received event.
- **getEventSource** (function) - Returns the underlying EventSource instance.
- **readyState** (number) - The current connection state (0: CONNECTING, 1: OPEN, 3: CLOSED).
### Request Example
```javascript
const { lastEvent, getEventSource, readyState } = useEventSource(
'http://localhost:3000/',
{
withCredentials: true,
events: {
message: (messageEvent) => { console.log(messageEvent); },
update: (messageEvent) => { console.log(messageEvent); },
},
}
);
```
```
--------------------------------
### useWebSocket getWebSocket Method
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=dependencies
Details the `getWebSocket` function and its usage for interacting with the underlying WebSocket instance, especially when sharing the WebSocket.
```APIDOC
## getWebSocket
### Description
If the WebSocket is shared, calling this function will lazily instantiate a `Proxy` instance that wraps the underlying WebSocket. You can get and set properties on the return value that will directly interact with the WebSocket, however certain properties/methods are protected (cannot invoke `close` or `send`, and cannot redefine any of the event handlers like `onmessage`, `onclose`, `onopen` and `onerror`). If the WebSocket is not shared (via options), then the return value is the underlying WebSocket, and thus methods such as `close` and `send` can be accessed and used.
### Type
```typescript
type getWebSocket = () => WebSocketLike | Proxy;
```
### Example
```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.'
}, []);
```
```
--------------------------------
### Reset Global State
Source: https://www.npmjs.com/package/react-use-websocket?activeTab=readme
Clears the library's global state for a specific URL, useful when managing connections across multiple windows.
```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');
});
}, []);
};
```
--------------------------------
### Interface Definition
Source: https://www.npmjs.com/package/react-use-websocket
TypeScript interface for the useWebSocket hook parameters and return values.
```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),
}
```