useWebSocket

Tags:
This Hook is available since v1.7.0.

A simplified React Hook for using WebSockets, wrapping the native WebSocket API, supporting features like automatic reconnection, heartbeat messages, and message queues.

Scenes

  • Persistent connection scenarios: For scenarios that require keeping a long-time connection with the server, such as instant messaging
  • Real-time data updates: To implement real-time data push updates for stocks, trades, etc.
  • Real-time interaction in game development: Syncing player status and game progress in multiplayer online games
  • Heartbeat detection and automatic reconnection: Ensuring stable connection, automatically handling disconnections and reconnections

Demo

Source

WS URL as Params

Edit the WS URL in the input field below and it will automatically reconnect when the URL changes.

WS URL:
wss://echo.websocket.org
Status:
Closed
No message received yet.

Programmatic WS URL

Edit the WS URL in the input field below and click the "Connect" button to establish a connection.

WS URL:
Status:
Closed
No message received yet.

Usage

const ws = useWebSocket(wsUrl, options) const ws = useWebSocket('wss://echo.websocket.org', { // Default is false, when configured to true, use default heartbeat configuration // Can also be configured as { interval: 5_000, message: 'ping', responseMessage: 'pong', responseTimeout: 1_000 } heartbeat: true, // Default is true, automatically reconnects when disconnected, configure as false to not reconnect // Can also be configured as { count: 3, interval: 1_000 } (default configuration) reconnect: true, // Filters out heartbeat messages responded by the server // filter: (event) => event.data === 'ping', // Lifecycle callbacks onOpen() { console.log('WebSocket connection opened') }, onMessage(message) { console.log('Received message', message) }, onError(error) { console.error('WebSocket connection error', error) }, onClose(event) { console.log('WebSocket connection closed', event) }, }) // ws.readyState // => 0 (CONNECTING), 1 (OPEN), 2 (CLOSING), 3 (CLOSED) // ws.send(data) // ws.close() // ws.open() // ws.ws // => WebSocket instance

Source

Click links below to view source on GitHub.

API

const ws = useWebSocket(wsUrl, options) // Or const ws = useWebSocket(options) ws.open(wsUrl)

WsUrl Connection String

A WebSocket URL string.

Options

export type UseWebSocketSendable = string | ArrayBufferLike | Blob | ArrayBufferView export interface UseWebSocketOptionsHeartbeat { /** * The heartbeat message to send. * * @defaultValue 'ping' */ message?: UseWebSocketSendable /** * The interval at which to send a heartbeat message. * * @defaultValue 1_000 */ interval?: number /** * The timeout for the server to respond to the heartbeat message. * * @defaultValue 1_000 */ responseTimeout?: number /** * The message considered as the server's response to the heartbeat, default to true, meaning any message returned is considered a heartbeat response (considered the server is alive) * * Can pass a message string, or a function that returns true if the message is considered a heartbeat response, to be used with responseTimeout, when timeout occurs, it is considered that the server is disconnected. * * @defaultValue true */ responseMessage?: true | UseWebSocketSendable | ((data: UseWebSocketSendable) => boolean) } export interface UseWebSocketOptionsReconnect { /** * The number of reconnection attempts, can be the number of retry attempts or a function returning a boolean, the function continues reconnecting when returning true, and stops when returning false. * * @defaultValue () => true */ count?: number | (() => boolean) /** * The interval between reconnection attempts. * * @defaultValue 1_000 */ interval?: number /** * A callback function when reconnection fails. */ onFailed?: (event: CloseEvent, ws: WebSocket) => void } export interface UseWebSocketOptions { /** * A callback function when WebSocket's open event is triggered. * * @defaultValue undefined */ onOpen?: (event: Event, ws: WebSocket) => void /** * A callback function when WebSocket's close event is triggered. * * @defaultValue undefined */ onClose?: (event: CloseEvent, ws: WebSocket) => void /** * A callback function when WebSocket's error event is triggered. * * @defaultValue undefined */ onError?: (event: Event, ws: WebSocket) => void /** * A callback function when WebSocket's message event is triggered. * * @defaultValue undefined */ onMessage?: (event: MessageEvent, ws: WebSocket) => void /** * A callback function that is called when the WebSocket connection fails to open, * such as an error or an invalid URL, which will cause the ws to fail to create a connection and close the connection. * * @defaultValue undefined */ onOpenFailed?: (event: CloseEvent, ws: WebSocket) => void /** * Heartbeat configuration, set to true to use default configuration, refer to UseWebSocketOptionsHeartbeat's default settings. * * @defaultValue false */ heartbeat?: boolean | UseWebSocketOptionsHeartbeat /** * Whether to automatically reconnect when the connection is dropped, count can be the number of retries or a function, the function continues reconnecting when returning true, and stops when returning false. * * @defaultValue true => { count: () => true, interval: 1_000 } */ reconnect?: boolean | UseWebSocketOptionsReconnect /** * Whether to immediately open the WebSocket connection, defaults to true when a WS URL is provided, otherwise false. */ immediate?: boolean /** * Whether to close the WebSocket connection when the component is unmounted. * * @defaultValue true */ closeOnUnmount?: boolean /** * Additional WebSocket subprotocols. * * @defaultValue [] */ protocols?: string | string[] /** * Filters messages to the `onMessage` callback, return `true` to ignore the message. * * Useful for filtering out heartbeat messages. * * @defaultValue undefined */ filter?: (event: MessageEvent, ws: WebSocket) => boolean }

Returns

export interface UseWebSocketReturns<HasURL extends boolean> { /** * The created WebSocket instance. */ ws: WebSocket | null /** * Send messages to the server. */ send: (data: UseWebSocketSendable) => void /** * The current state of the WebSocket connection. */ readyState: UseWebSocketReturnsReadyState /** * Close the WebSocket connection. */ close: () => Promise<void> /** * Open the WebSocket connection, closes the old connection if it exists. */ open: HasURL extends true ? () => Promise<void> : (wsUrl?: string, protocols?: string | string[]) => Promise<void> } export type UseWebSocketReturnsReadyState = | typeof WebSocket.CONNECTING | typeof WebSocket.OPEN | typeof WebSocket.CLOSING | typeof WebSocket.CLOSED