{"id":11901,"library":"react-use-websocket","title":"React WebSocket Hook","description":"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.","status":"active","version":"4.13.0","language":"javascript","source_language":"en","source_url":"https://github.com/robtaussig/react-use-websocket","tags":["javascript","react","react-hooks","websocket","websockets","typescript"],"install":[{"cmd":"npm install react-use-websocket","lang":"bash","label":"npm"},{"cmd":"yarn add react-use-websocket","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-use-websocket","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency. v4.x requires React 18+; v3.x supports React 17.","package":"react","optional":false}],"imports":[{"note":"useWebSocket is a named export, not a default export. CommonJS require is not supported in modern React/ESM projects.","wrong":"import useWebSocket from 'react-use-websocket';\nconst useWebSocket = require('react-use-websocket');","symbol":"useWebSocket","correct":"import { useWebSocket } from 'react-use-websocket';"},{"note":"ReadyState is an enum representing the WebSocket connection status, used for conditional rendering or logic.","wrong":"import ReadyState from 'react-use-websocket';","symbol":"ReadyState","correct":"import { ReadyState } from 'react-use-websocket';"},{"note":"When importing types like Options, it's best practice to use 'import type' for clarity and to ensure they are stripped during compilation.","wrong":"import { Options } from 'react-use-websocket';","symbol":"Options","correct":"import type { Options } from 'react-use-websocket';"}],"quickstart":{"code":"import React, { useState, useCallback, useEffect } from 'react';\nimport useWebSocket, { ReadyState } from 'react-use-websocket';\n\nexport const WebSocketDemo = () => {\n  // Public API that will echo messages sent to it back to the client\n  const [socketUrl, setSocketUrl] = useState('wss://echo.websocket.org');\n  const [messageHistory, setMessageHistory] = useState([]);\n\n  const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);\n\n  useEffect(() => {\n    if (lastMessage !== null) {\n      setMessageHistory((prev) => prev.concat(lastMessage.data));\n    }\n  }, [lastMessage]);\n\n  const handleClickChangeSocketUrl = useCallback(\n    () => setSocketUrl('wss://demos.kaazing.com/echo'),\n    []\n  );\n\n  const handleClickSendMessage = useCallback(() => sendMessage('Hello'), []);\n\n  const connectionStatus = {\n    [ReadyState.CONNECTING]: 'Connecting',\n    [ReadyState.OPEN]: 'Open',\n    [ReadyState.CLOSING]: 'Closing',\n    [ReadyState.CLOSED]: 'Closed',\n    [ReadyState.UNINSTANTIATED]: 'Uninstantiated',\n  }[readyState];\n\n  return (\n    <div>\n      <button onClick={handleClickChangeSocketUrl}>\n        Click Me to change Socket Url\n      </button>\n      <button\n        onClick={handleClickSendMessage}\n        disabled={readyState !== ReadyState.OPEN}\n      >\n        Click Me to send 'Hello'\n      </button>\n      <span>The WebSocket is currently {connectionStatus}</span>\n      {lastMessage ? <span>Last message: {lastMessage.data}</span> : null}\n      <h3>Message History:</h3>\n      <ul>\n        {messageHistory.map((message, idx) => (\n          <li key={idx}>{message}</li>\n        ))}\n      </ul>\n    </div>\n  );\n};","lang":"typescript","description":"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."},"warnings":[{"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`).","message":"Version 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.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Update your hook usage from `const [sendMessage, lastMessage, readyState] = useWebSocket(...)` to `const { sendMessage, lastMessage, readyState } = useWebSocket(...)`.","message":"In version 2.0.0, the return value of the `useWebSocket` hook changed from an array to an object. Destructuring must be updated accordingly.","severity":"breaking","affected_versions":">=2.0.0 <4.0.0"},{"fix":"Use a reliable WebSocket echo server (e.g., `wss://echo.websocket.org`) or your own backend for testing and production environments.","message":"The `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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Prefer `useWebSocket(socketUrl, options, false)` for explicit unsubscription or closing.","message":"To 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.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you are using `import { useWebSocket } from 'react-use-websocket';` and your project is configured for ESM if applicable.","cause":"Incorrect import statement (e.g., default import instead of named) or trying to use CommonJS `require` in an ESM context.","error":"TypeError: useWebSocket is not a function"},{"fix":"Ensure `useWebSocket` is only invoked directly within the body of a React function component or another custom hook.","cause":"The `useWebSocket` hook is being called outside of a React function component or a custom hook.","error":"Error: Invalid hook call. Hooks can only be called inside of the body of a function component."},{"fix":"Change the `socketUrl` to a more reliable endpoint like `wss://echo.websocket.org` for testing, or use a trusted production WebSocket server.","cause":"The `demos.kaazing.com/echo` server is frequently offline or unreachable, causing connection attempts to fail.","error":"WebSocket connection failed: wss://demos.kaazing.com/echo"}],"ecosystem":"npm"}