Docs
WebSocket

WebSocket

A hook for WebSocket.

About

The useWebSocket hook is a custom React hook that manages a WebSocket connection. It provides an easy-to-use interface for connecting, disconnecting, and sending messages through a WebSocket, along with handling reconnection logic and various WebSocket events.

Parameters

NameTypeDescription
socketUrlstringRequired, webSocket url.
optionsOptionsconnect the configuration item.

Return Values

NameTypeDescription
latestMessageWebSocketEventMap['message']Latest message
sendMessageWebSocket['send']Send message function
disconnect() => voidDisconnect webSocket manually
connect() => voidConnect webSocket manually. If already connected, close the current one and reconnect.
readyStateReadyStateCurrent webSocket connection status
webSocketInsWebSocketWebSocket instance

Options

NameTypeDescriptionDefault
onOpen(event: WebSocketEventMap['open'], instance: WebSocket) => voidThe webSocket connect callback-
onClose(event: WebSocketEventMap['close'], instance: WebSocket) => voidWebSocket close callback-
onMessage(message: WebSocketEventMap['message'], instance: WebSocket) => voidWebSocket receive message callback-
onError(event: WebSocketEventMap['error'], instance: WebSocket) => voidWebSocket error callback.-
reconnectLimitnumberRetry times3
reconnectIntervalnumberRetry interval(ms)3000
manualbooleanManually starts connectionfalse
protocolsstring | string[]Sub protocols-

Installation

Run the following command:

npx scriptkavi-hooks@latest add web-socket

Usage

import { useWebSocket } from "@/hooks/web-socket"
import React, { useEffect } from "react"
 
function WebSocketComponent() {
  const socketUrl = "wss://example.com/socket"
  const { latestMessage, sendMessage, connect, disconnect, readyState } =
    useWebSocket(socketUrl, {
      onOpen: () => console.log("WebSocket connection opened"),
      onClose: () => console.log("WebSocket connection closed"),
      onMessage: (message) => console.log("Received message:", message.data),
      onError: (error) => console.error("WebSocket error:", error),
    })
 
  useEffect(() => {
    if (readyState === ReadyState.Open) {
      sendMessage("Hello, WebSocket!")
    }
  }, [readyState])
 
  return (
    <div>
      <button onClick={connect}>Connect</button>
      <button onClick={disconnect}>Disconnect</button>
      <div>Ready State: {readyState}</div>
      <div>Latest Message: {latestMessage?.data}</div>
    </div>
  )
}
 
export default WebSocketComponent