Registry / http-networking / react-use-websocket

react-use-websocket

JSON →
library4.13.0jsnpmunverified

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-websocket
INSTALL
IMPORT
SIG · REACT-USE-WEBSOCKE
R
react-use-websocket
http-networkingjavascriptv4.13.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

useWebSocket
import { useWebSocket } from 'react-use-websocket';
import useWebSocket from 'react-use-websocket'; const useWebSocket = require('react-use-websocket');
useWebSocket is a named export, not a default export. CommonJS require is not supported in modern React/ESM projects.
ReadyState
import { ReadyState } from 'react-use-websocket';
import ReadyState from 'react-use-websocket';
ReadyState is an enum representing the WebSocket connection status, used for conditional rendering or logic.
Options
import type { Options } from 'react-use-websocket';
import { Options } from 'react-use-websocket';
When importing types like Options, it's best practice to use 'import type' for clarity and to ensure they are stripped during compilation.

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.

import React, { useState, useCallback, useEffect } from 'react'; import useWebSocket, { ReadyState } from 'react-use-websocket'; export const WebSocketDemo = () => { // Public API that will echo messages sent to it back to the client const [socketUrl, setSocketUrl] = useState('wss://echo.websocket.org'); const [messageHistory, setMessageHistory] = useState([]); const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl); useEffect(() => { if (lastMessage !== null) { setMessageHistory((prev) => prev.concat(lastMessage.data)); } }, [lastMessage]); const handleClickChangeSocketUrl = useCallback( () => setSocketUrl('wss://demos.kaazing.com/echo'), [] ); const handleClickSendMessage = useCallback(() => sendMessage('Hello'), []); const connectionStatus = { [ReadyState.CONNECTING]: 'Connecting', [ReadyState.OPEN]: 'Open', [ReadyState.CLOSING]: 'Closing', [ReadyState.CLOSED]: 'Closed', [ReadyState.UNINSTANTIATED]: 'Uninstantiated', }[readyState]; return ( <div> <button onClick={handleClickChangeSocketUrl}> Click Me to change Socket Url </button> <button onClick={handleClickSendMessage} disabled={readyState !== ReadyState.OPEN} > Click Me to send 'Hello' </button> <span>The WebSocket is currently {connectionStatus}</span> {lastMessage ? <span>Last message: {lastMessage.data}</span> : null} <h3>Message History:</h3> <ul> {messageHistory.map((message, idx) => ( <li key={idx}>{message}</li> ))} </ul> </div> ); };
Debug
Known issues
breakingVersion 4.0.0 and above of `react-use-websocket` now depends on React 18. If your project is still on React 17 or older, you must install version 3.0.0.
fix
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`).
affects: >=4.0.0
breakingIn version 2.0.0, the return value of the `useWebSocket` hook changed from an array to an object. Destructuring must be updated accordingly.
fix
Update your hook usage from `const [sendMessage, lastMessage, readyState] = useWebSocket(...)` to `const { sendMessage, lastMessage, readyState } = useWebSocket(...)`.
affects: >=2.0.0 <4.0.0
gotchaThe `wss://demos.kaazing.com/echo` endpoint, often used in examples, has been intermittently unavailable. Relying on it for production or critical testing is not advised as it will lead to connection failures.
fix
Use a reliable WebSocket echo server (e.g., `wss://echo.websocket.org`) or your own backend for testing and production environments.
affects: >=1.0.0
gotchaTo explicitly close or unsubscribe a component from a WebSocket connection, passing `false` as the third parameter to `useWebSocket` is the recommended method since v2.0.0. While setting `socketUrl` to `null` still works, it's less explicit.
fix
Prefer `useWebSocket(socketUrl, options, false)` for explicit unsubscription or closing.
affects: >=2.0.0
Errors
Common errors & fixes
TypeError: useWebSocket is not a function
Incorrect import statement (e.g., default import instead of named) or trying to use CommonJS `require` in an ESM context.
fix
Ensure you are using `import { useWebSocket } from 'react-use-websocket';` and your project is configured for ESM if applicable.
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
The `useWebSocket` hook is being called outside of a React function component or a custom hook.
fix
Ensure `useWebSocket` is only invoked directly within the body of a React function component or another custom hook.
WebSocket connection failed: wss://demos.kaazing.com/echo
The `demos.kaazing.com/echo` server is frequently offline or unreachable, causing connection attempts to fail.
fix
Change the `socketUrl` to a more reliable endpoint like `wss://echo.websocket.org` for testing, or use a trusted production WebSocket server.
Upgrade
Version history
4.13.0latest on npm
Audit
Dependencies
reactrequiredPeer dependency. v4.x requires React 18+; v3.x supports React 17.
Agent activity
4 hits · last 30 days
node
4
Resources
react-use-websocket — npm install react-use-websocket · libregistry