useWebSocket
WebSocket client designed for React.
Features
- Built-in Validation: Validate messages with zod, valibot, arktype or with a simple function.
- Connection Reuse: Share a WebSocket connection across multiple hook instances.
- Automatic Reconnect: Configurable reconnection strategies for resilient connections.
- Ping Support: Built-in ping to keep connections alive.
- Message Queueing: Outgoing messages are queued while connecting.
- Automatic Parsing/Serialization: Customizable message parsing and serialization.
- Friendly API: Simple, ergonomic API for sending messages and tracking connection state.
Installation
Quick Start
Send and Receive messages
Connect to a WebSocket server, validate and handle incoming messages.
Use the send
method the send messages to the server.
All hooks using the same url + protocol share a single WebSocket connection. \
Validation
The validate
option ensures incoming messages match your expected format, providing both runtime validation and type safety.
👉 Functional validation
For simple cases you can use a function to validate the incoming message.
👉 Schema validation
For more complex cases you can use a schema to validate the cookie value. Compatible validation libraries include zod 3.24+, valibot 1.0+ or arktype 2.0+. Check out Standard Schema for more info.
Message Filtering
Sometimes you need to selectively process messages based on their content. Rather than writing complex validation logic to handle every possible message format, you can simply ignore unwanted messages.
Return null | undefined
from the validate
option to skip processing specific messages. The hook will silently ignore these messages and only trigger onMessage
for validated ones.
Note that returning null
or undefined
from the parseMessage
option will also ignore messages.
Custom Parsing/Serialization
You can configure default message parsing and serialization in defineWebSocket
, while still having the flexibility to override these settings in individual useWebSocket
calls.
Since JSON parsing and serialization are the default behavior, you typically won't need to customize these settings.
Typesafe message sending
Type the serializeMessage
parameter to constrain what messages can be sent through the send
method.
Now the send
method only accepts messages matching the OutgoingMessage
type.
Closing the connection
The WebSocket connection automatically closes when there are no more active listeners. The listeners are removed when
- the hook unmounts
- The url is set to
null
Note that if the connection closes for any other reason (like network issues, server-side closure or using the close method of the WebSocket instance directly), the configured reconnection strategy will attempt to restore the connection.
API Reference
👉 defineWebSocket
DefineWebSocketOptions
Options for defineWebSocket.
Prop | Type | Default |
---|---|---|
serializeMessage? | Function | - |
parseMessage? | Function | - |
binaryType? | BinaryType | - |
ping? | WebSocketPingOption | - |
reconnect? | WebSocketReconnectOption | - |
WebSocketPingOption
The ping options.
Prop | Type | Default |
---|---|---|
leading? | boolean | false |
message? | string | 'ping' |
interval | number | - |
WebSocketReconnectOption
The reconnect options.
Prop | Type | Default |
---|---|---|
attempts? | number | Infinity |
delay | Function | - |
when? | Function | () => true |
👉 useWebSocket
Send and Receive messages from a WebSocket server.
UseWebSocketOptions
Options for the useWebSocket hook.
Prop | Type | Default |
---|---|---|
onError? | ((event: Event) => void) | - |
onClose? | ((event: CloseEvent) => void) | - |
onOpen? | ((event: Event) => void) | - |
onMessage? | (message: T, event: MessageEvent) => void | - |
serializeMessage? | Function | - |
validate? | TValidator | - |
parseMessage? | (event: MessageEvent) => MaybePromise<T> | - |
protocols? | string | string[] | - |
url | string | URL | Falsy | - |
UseWebSocketReturn
Return value of the useWebSocket hook.
Prop | Type | Default |
---|---|---|
state | "connecting" | "open" | "closed" | - |
send | (message: TSendMessage) => void | - |