{"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.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install react-use-websocket"],"cli":null},"imports":["import { useWebSocket } from 'react-use-websocket';","import { ReadyState } from 'react-use-websocket';","import type { Options } from 'react-use-websocket';"],"auth":{"required":false,"env_vars":[]},"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.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}