react-use-websocket is a React Hook designed to simplify and robustly integrate WebSocket communication into React components. It provides a straightforward API for managing WebSocket connections, sending messages, and reacting to incoming data and connection state changes. The current stable version is 4.13.0, which has a peer dependency on React 18. For applications still using React 17, version 3.0.0 is recommended. The library focuses on ease of use, offering features like automatic JSON serialization/deserialization for messages, memoized `sendMessage` callbacks, and options for sharing a single WebSocket connection across multiple components. Its release cadence is moderate, with significant breaking changes typically aligned with major React versions or substantial API overhauls. A key differentiator is its robust handling of connection failures and an explicit API for managing the connection lifecycle, alongside experimental Socket.IO support.
npm install react-use-websocketVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates setting up a basic WebSocket connection using `useWebSocket`, sending messages, and displaying incoming messages and the connection status in a React component.
Upgrade your project to React 18, or install `react-use-websocket@3.0.0` if you need to stay on an older React version (e.g., `npm install --save react-use-websocket@3.0.0`).
Update your hook usage from `const [sendMessage, lastMessage, readyState] = useWebSocket(...)` to `const { sendMessage, lastMessage, readyState } = useWebSocket(...)`.Use a reliable WebSocket echo server (e.g., `wss://echo.websocket.org`) or your own backend for testing and production environments.
Prefer `useWebSocket(socketUrl, options, false)` for explicit unsubscription or closing.
Ensure you are using `import { useWebSocket } from 'react-use-websocket';` and your project is configured for ESM if applicable.Ensure `useWebSocket` is only invoked directly within the body of a React function component or another custom hook.
Change the `socketUrl` to a more reliable endpoint like `wss://echo.websocket.org` for testing, or use a trusted production WebSocket server.