← Back to archive

Repo of the Day

robtaussig/react-use-websocket

Published: Dec 3, 2023

Open repository ↗

React Hook for WebSocket communication

Summary

react-use-websocket is a React Hook for managing WebSocket connections from functional components, written in TypeScript under the MIT license. It bundles the plumbing most teams end up rewriting (reconnect logic, message queuing, JSON parsing, sharing one socket across multiple components) behind a single hook. The library also ships sister hooks for Socket.IO and server-sent events.

What it is useful for

Adding real-time data to a React app where the client and server already speak WebSocket: chat panels, live dashboards, notification streams, presence indicators, or multiplayer game state. The share: true option is useful when several components on the same page need data from the same endpoint, since only one underlying socket is opened and reference-counted, and closed automatically when the last subscriber unmounts. The library also exposes useSocketIO for Socket.IO backends and useEventSource for server-sent-events, so the same hook-based ergonomics extend to those transports. Built-in heartbeat and reconnect strategies help with flaky mobile or proxied networks.

How engineers can use it

Install with npm install react-use-websocket and call the hook from a functional component:

import useWebSocket, { ReadyState } from 'react-use-websocket';

const { sendMessage, sendJsonMessage, lastMessage, lastJsonMessage, readyState }
  = useWebSocket('wss://echo.websocket.org', {
    shouldReconnect: () => true,
    reconnectAttempts: 10,
    reconnectInterval: 3000,
  });

sendMessage and sendJsonMessage are memoized callbacks. Messages sent before the socket is open are queued and flushed on connect. lastMessage is the raw MessageEvent; lastJsonMessage is the parsed object, or an empty object if the payload is not JSON-parseable. A third argument, shouldConnect, lets you suspend the connection by passing false. The options object also covers heartbeat (ping/pong with timeout), filter (drop messages to avoid re-renders), queryParams, protocols, and onOpen/onClose/onMessage/onError callbacks. For Socket.IO servers, import useSocketIO; for SSE, import useEventSource. resetGlobalState(url) is provided for the documented window.open scenario where child windows need to release a shared socket.

Documented requirements and limitations: React 16.8+ is required, and version 4.0.0 depends on React 18 (install [email protected] if you cannot upgrade). The hook cannot be used inside class components. The README warns that the public demo endpoint wss://demos.kaazing.com/echo has been down, so the hosted demo may fail to connect; point the hook at your own server or a working echo service for testing.