shadcn-ahooks

useWebSocket

A hook for WebSocket.

Overview

A hook for WebSocket.

Documentation and Examples

Installation

Open in
pnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useWebSocket.json
npx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useWebSocket.json
yarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useWebSocket.json
bun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useWebSocket.json

A hook for WebSocket.

Examples

Default usage

API

enum ReadyState {
  Connecting = 0,
  Open = 1,
  Closing = 2,
  Closed = 3,
}

interface Options {
  reconnectLimit?: number;
  reconnectInterval?: number;
  onOpen?: (event: WebSocketEventMap['open'], instance: WebSocket) => void;
  onClose?: (event: WebSocketEventMap['close'], instance: WebSocket) => void;
  onMessage?: (message: WebSocketEventMap['message'], instance: WebSocket) => void;
  onError?: (event: WebSocketEventMap['error'], instance: WebSocket) => void;
  protocols?: string | string[];
}

interface Result {
  latestMessage?: WebSocketEventMap['message'];
  sendMessage: WebSocket['send'];
  disconnect: () => void;
  connect: () => void;
  readyState: ReadyState;
  webSocketIns?: WebSocket;
}

useWebSocket(socketUrl: string, options?: Options): Result;

Params

| Property | Description | Type | Default | | | - | | socketUrl | Required, webSocket url | string | - | | options | connect the configuration item | Options | - |

Options

| Options Property | Description | Type | Default | | - | - | -- | | | latestMessage | Latest message | WebSocketEventMap['message'] | | sendMessage | Send message function | WebSocket['send'] | | disconnect | Disconnect webSocket manually | () => void | | connect | Connect webSocket manually. If already connected, close the current one and reconnect. | () => void | | readyState | Current webSocket connection status | ReadyState | | webSocketIns | WebSocket instance | WebSocket |

On this page