Skip to content
On this page

useWebSocket

A hook for WebSocket.

Code demonstration

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;
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

PropertyDescriptionTypeDefault
socketUrlRequired, webSocket urlstring-
optionsconnect the configuration itemOptions-

Options

PropertyDescriptionTypeDefault
onOpenThe webSocket connect callback(event: WebSocketEventMap['open'], instance: WebSocket) => void-
onCloseWebSocket close callback(event: WebSocketEventMap['close'], instance: WebSocket) => void-
onMessageWebSocket receive message callback(message: WebSocketEventMap['message'], instance: WebSocket) => void-
onErrorWebSocket error callback(event: WebSocketEventMap['error'], instance: WebSocket) => void-
reconnectLimitRetry timesnumber3
reconnectIntervalRetry interval(ms)number3000
manualManually starts connectionbooleanfalse
protocolsSub protocolsstring | string[]-

Result

PropertyDescriptionType
latestMessageLatest messageRef<WebSocketEventMap['message']>
sendMessageSend message functionWebSocket['send']
disconnectDisconnect webSocket manually() => void
connectConnect webSocket manually. If already connected, close the current one and reconnect.() => void
readyStateCurrent webSocket connection statusRef<ReadyState>
webSocketInsWebSocket instanceWebSocket

Source

SourceDocsDemo