Skip to content

useWebSocket

Hook that connects to a WebSocket server and handles incoming and outgoing messages

browser
medium
test coverage
Last changed: 7 months ago

TIP

This hook uses WebSocket browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation

Library
CLI
Manual
typescript
import { useWebSocket } from '@siberiacancode/reactuse';

Usage

typescript
const { status, close, send, open, client } = useWebSocket('url');

Demo

Api

Parameters

NameTypeDefaultNote
urlUseWebSocketUrl-The URL of the WebSocket server
options.onConnected?(webSocket: WebSocket) => void-The callback function that is called when the WebSocket connection is established
options.onDisconnected?(event: CloseEvent, webSocket: WebSocket) => void-The callback function that is called when the WebSocket connection is closed
options.onError?(event: Event, webSocket: WebSocket) => void-The callback function that is called when an error occurs
options.onMessage?(event: MessageEvent, webSocket: WebSocket) => void-The callback function that is called when a message is received
options.retry?boolean | number-The number of times to retry the connection
options.protocols?Array<'soap' | 'wasm'>-The list of protocols to use

Returns

UseWebSocketReturn

Type declaration

typescript
export type UseWebSocketUrl = (() => string) | string;

export interface UseWebSocketOptions {
  /** The list of protocols to use */
  protocols?: Array<'soap' | 'wasm'>;
  /** The number of times to retry the connection */
  retry?: boolean | number;
  /** The callback function that is called when the WebSocket connection is established */
  onConnected?: (webSocket: WebSocket) => void;
  /** The callback function that is called when the WebSocket connection is closed */
  onDisconnected?: (event: CloseEvent, webSocket: WebSocket) => void;
  /** The callback function that is called when an error occurs */
  onError?: (event: Event, webSocket: WebSocket) => void;
  /** The callback function that is called when a message is received */
  onMessage?: (event: MessageEvent, webSocket: WebSocket) => void;
}

export type UseWebSocketStatus = 'connected' | 'connecting' | 'disconnected' | 'failed';

export interface UseWebSocketReturn {
  /** The WebSocket client */
  client?: WebSocket;
  /** The close function */
  close: WebSocket['close'];
  /** The send function */
  send: WebSocket['send'];
  /** The status of the WebSocket connection */
  status: UseWebSocketStatus;
  /** The open function */
  open: () => void;
}

Source

SourceDemo

Contributors

D
debabin
debabin
H
hywax
hywax
А
Алдияр Сейлханов
Алдияр Сейлханов

Released under the MIT License.