WarningCalling send() while isConnected is false will not queue the message; the operation will fail and update the error state immediately.
TipThis hook automatically attempts to parse incoming message data as JSON. If the data is not a valid JSON string, it will return the raw message.
The useWebsocket hook simplifies full-duplex communication in React applications by encapsulating the native WebSocket API. It automatically handles the connection lifecycle, provides reactive states for connection status and incoming data, and includes a configurable exponential-like reconnection mechanism for when connections are lost unexpectedly. It also handles JSON parsing by default and ensures clean resource disposal upon component unmounting.
| Name | Type | Description |
|---|---|---|
| url | string | The WebSocket URL to connect to (e.g., wss://echo.websocket.org). Required. |
| autoConnect | boolean | If true, the socket connects immediately on mount. Default: true. |
| maxRetries | number | Maximum number of reconnection attempts before giving up. Default: Infinity. |
| reconnectionInterval | number | Delay in milliseconds between reconnection attempts. Default: 3000. |
| onMessage | (message: T) => void | Callback triggered whenever a new message is successfully received and parsed. |
| onClose | (event: CloseEvent) => void | Callback triggered when the connection is closed. |
| onError | (event: Event) => void | Callback triggered when a connection error occurs. |
| Name | Type | Description |
|---|---|---|
| connect | () => void | Manually connect the Websocket. |
| isConnected | boolean | Reactive state indicating if the connection is currently open. |
| message | T | null | The most recently received and parsed message. |
| messages | T[] | An array containing the history of all messages received during the current session. |
| error | string | Contains the error message if a connection or parsing error occurs. |
| send | (data) => void | Function to transmit data through the socket. |
| disconnect | () => void | Manually closes the connection and cancels any pending reconnection timers. |