useWebsocket

A comprehensive React hook for managing WebSocket connections with built-in auto-reconnection logic, message history, and SSR safety.

Warning

Calling send() while isConnected is false will not queue the message; the operation will fail and update the error state immediately.

Tip

This 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.

Installation

bash

Description

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.

Parameters

NameTypeDescription
urlstringThe WebSocket URL to connect to (e.g., wss://echo.websocket.org). Required.
autoConnectbooleanIf true, the socket connects immediately on mount. Default: true.
maxRetriesnumberMaximum number of reconnection attempts before giving up. Default: Infinity.
reconnectionIntervalnumberDelay in milliseconds between reconnection attempts. Default: 3000.
onMessage(message: T) => voidCallback triggered whenever a new message is successfully received and parsed.
onClose(event: CloseEvent) => voidCallback triggered when the connection is closed.
onError(event: Event) => voidCallback triggered when a connection error occurs.

Return values

NameTypeDescription
connect() => voidManually connect the Websocket.
isConnectedbooleanReactive state indicating if the connection is currently open.
messageT | nullThe most recently received and parsed message.
messagesT[]An array containing the history of all messages received during the current session.
errorstringContains the error message if a connection or parsing error occurs.
send(data) => voidFunction to transmit data through the socket.
disconnect() => voidManually closes the connection and cancels any pending reconnection timers.

Demo

Websocket

Source code

tsx