useWebSocket

React hook to manage WebSocket connections with auto-reconnect, message handlers, and connection state callbacks.

pnpm add react-callback-hooks

Demo

Connectingecho.websocket.events
Send a message to see the echo

Usage

Simple — URL + optional onMessage callback:

import { useWebSocket } from 'react-callback-hooks'

const { send, readyState, lastMessage } = useWebSocket(
  'wss://example.com/ws',
  (event) => console.log('received', event.data)
)

Object form — full control:

const { send, disconnect, readyState, lastMessage } = useWebSocket({
  url: 'wss://example.com/ws',
  reconnect: true,
  reconnectDelay: 3_000,
  onMessage: (event) => console.log('received', event.data),
  onOpen: (event) => console.log('connected'),
  onClose: (event) => console.log('disconnected'),
  onError: (event) => console.error('error', event)
})

send('hello')
disconnect()

Parameters

Simple form

ParameterTypeDescription
urlstringWebSocket server URL.
onMessage(event: MessageEvent) => voidOptional. Fires on each incoming message.

Object form

PropertyTypeDefaultDescription
urlstringWebSocket server URL. Changing this reconnects to the new URL.
onMessage(event: MessageEvent) => voidFires on each incoming message.
onOpen(event: Event) => voidFires when the connection opens.
onClose(event: CloseEvent) => voidFires when the connection closes.
onError(event: Event) => voidFires on connection error.
reconnectbooleanfalseAutomatically reconnect after the connection closes.
reconnectDelaynumber3000Delay in ms before attempting to reconnect.

Return Values

PropertyTypeDescription
send(data: string | Blob | ...) => voidSends data. No-op if the socket is not open.
disconnect() => voidCloses the connection and cancels any pending reconnect.
readyState0 | 1 | 2 | 3CONNECTING | OPEN | CLOSING | CLOSED.
lastMessageMessageEvent | nullThe most recent message event.