useWebSocket
Connect to a WebSocket and re-render with its status and latest message.
Usage
With a URL
Every component that passes the same URL (and the same protocols) shares one connection. The first component to mount with a URL creates it, and its connection options are used for everyone. A render React throws away doesn't count. Options passed by later components for the same URL are ignored, except handlers and enabled, which are per component. In development, a later component that passes different connection options logs a warning naming them. If two components need different options for the same URL, create separate clients with createWebSocket.
Changing url closes the old connection (once nothing else uses it) and opens the new one.
With a client
Connection options come from createWebSocket. Only handlers and enabled are accepted here.
Disconnected
Pass null or undefined to stay disconnected. The status is 'idle', and send returns false without queueing.
Parameters
Options
With a URL, options accepts every connection option plus the handlers below.
Handlers
Handlers always see the latest props and state, and changing them never reconnects. You don't need useCallback, useEffectEvent or the React Compiler for that.
Handlers belong to the component: they run only while it is mounted and enabled. Every component sharing a connection receives every event.
Returns
UseWebSocketResult<In, Out>:
send, close and reconnect keep the same identity across renders, so they are safe in dependency arrays and as props to memoized children.
Behavior
- Renders. The component re-renders when the status changes and on every message. For high-frequency streams, use
useWebSocketEventanduseWebSocketStatus, which don't re-render per message. See Performance. - Lifecycle. The connection opens on mount (in an Effect) and closes one tick after the last component using it unmounts. StrictMode and
<Activity>don't create duplicate sockets. See StrictMode, Activity and lifecycle. - Server rendering. Renders
status: 'idle'and never connects. See Server rendering. - After
close(). The status stays'closed'while components remain mounted. Callreconnect()to start again. Once every component unmounts, the next mount connects normally, as it does after aclose()while none was mounted.
Caveats
useWebSocket(url)with the same URL but differentjson,schemaorreconnectoptions in two components uses the first component's options for both, and warns in development. UsecreateWebSocketinstead.lastMessageis for "show the latest value" UIs. Don't collect messages by watching it in an Effect: if several messages arrive before React renders, you only see the last one. UseonMessageinstead, which runs once per message.