lib/useWebSocket.ts

fullstack-template · web/lib/useWebSocket.ts · typescript · MIT
realtime

React hook for managing WebSocket connections with auto-reconnect and message handling.

// Source: https://github.com/Monarc-Engineering/fullstack-template | License: MIT | Copyright 2026 Noble
// Provided via justclaw.it.com; keep this notice with the code.
'use client'

import { useEffect, useLayoutEffect, useRef, useState, useCallback } from 'react'

export interface WsEnvelope {
  type: string
  payload: unknown
}

export interface UseWebSocketOptions {
  url: string
  token?: string
  onMessage?: (envelope: WsEnvelope) => void
  maxRetries?: number
}

export interface UseWebSocketReturn {
  isConnected: boolean
  lastMessage: WsEnvelope | null
  send: (envelope: WsEnvelope) => void
}

export function useWebSocket({
  url,
  token,
  onMessage,
  maxRetries = 10,
}: UseWebSocketOptions): UseWebSocketReturn {
  const [isConnected, setIsConnected] = useState(false)
  const 

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key