one-hook
Size
1.41 kb
View source

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

npm install @1hook/use-websocket

Quick Start

Setup the WebSocket

Define the ping and reconnect strategies for the useWebSocket hook.

websocket.ts
import {  } from 'zod'
import {  } from '@1hook/use-websocket'

export const  = ({
  : { : 10000 },
  : { : 5000 },
})

Send and Receive messages

Connect to a WebSocket server, validate and handle incoming messages.

const {  } = ({
  : 'wss://echo.websocket.org',
  : .({ : .() }),
  : .,
})

Use the send method the send messages to the server.

send({ text: 'Hello!' })

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.

({
  : 'wss://echo.websocket.org',
  : () => (),
  : () => {
    // message: string
  },
})

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

({
  : 'wss://echo.websocket.org',
  : .({ : .(), : .() }),
  : () => {
    // message: { type: string, text: string }
  },
})

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.

({
  : 'wss://echo.websocket.org',
  : 
    .({ : .(), : .() })
    .() // allows returning null from catch() to ignore invalid messages
    .(null),
  : () => {
    // message: { type: string, text: string }
  },
})

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.

({
  () {
    if (typeof . !== 'string') return .
    return .(.)
  },
  () {
    return .()
  },
})

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.

type  = { : string; : string }

const {  } = ({
  : 'wss://echo.websocket.org',
  (: ) {
    return .()
  },
})

Now the send method only accepts messages matching the OutgoingMessage type.

// ✅ ok
({ : 'hello', : 'world' })

// ❌ error
({ : 'hello', : 123 })

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.

({
  :  ? 'wss://echo.websocket.org' : null,
})

API Reference

👉 defineWebSocket

function defineWebSocket(options: DefineWebSocketOptions): useWebSocket

DefineWebSocketOptions

Options for defineWebSocket.

PropTypeDefault
serializeMessage?
Function
-
parseMessage?
Function
-
binaryType?
BinaryType
-
ping?
WebSocketPingOption
-
reconnect?
WebSocketReconnectOption
-

WebSocketPingOption

The ping options.

PropTypeDefault
leading?
boolean
false
message?
string
'ping'
interval
number
-

WebSocketReconnectOption

The reconnect options.

PropTypeDefault
attempts?
number
Infinity
delay
Function
-
when?
Function
() => true

👉 useWebSocket

Send and Receive messages from a WebSocket server.

function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn

UseWebSocketOptions

Options for the useWebSocket hook.

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

PropTypeDefault
state
"connecting" | "open" | "closed"
-
send
(message: TSendMessage) => void
-

On this page