#API reference
Everything the package exports. All exports are typed, and every type has inline documentation that your editor shows on hover.
#Entry points
| Import | Contents | Notes |
|---|---|---|
react-websocket | Hooks, createWebSocket, MessageError, types | Marked 'use client' for Server Components frameworks |
react-websocket/core | createWebSocket, the other create* functions, MessageError, types | No React dependency. Use it in workers, Node, or other frameworks |
react-websocket/timeline | createWebSocketTimeline, its types | For multiplayer games. No React dependency |
react-websocket/ag-ui | createAgUiAgent, applyAgUiEvent, applyPatch, their types | AG-UI agents over a WebSocket. No React dependency |
react-websocket/outbox | createWebSocketOutbox, indexedDBStorage, memoryStorage, their types | Messages kept until acknowledged, across reloads. No React dependency |
react-websocket/webtransport | createWebTransportSocket, its types | WebTransport behind the same API, with a WebSocket fallback. No React dependency |
react-websocket/tabs | createTabsWebSocket, its types | One connection shared by every tab. No React dependency |
react-websocket/devtools | WebSocketDevtools, its props | A development panel showing every client. Marked 'use client' |
react-websocket/replay | createRecordingWebSocket, createReplayWebSocket, their types | Record sessions and replay them without a server. No React dependency |
react-websocket/chaos | createChaosWebSocket, its types | A development tool. No React dependency |
Every entry point ships as ESM and CommonJS with type declarations for each.
#Hooks
| Hook | Use it to | Re-renders on |
|---|---|---|
useWebSocket(url | client, options?) | Connect and read status and the latest message | Status changes and every message |
useWebSocketEvent(client, type, listener) | Handle events without re-rendering | Never |
useWebSocketStatus(client) | Show connection status | Status changes only |
useWebSocketTopic(topics, topic) | Hold topic subscriptions that survive reconnects | Never |
useWebSocketState(store, selector?, isEqual?) | Read state reduced from messages | The selected value changes |
useWebSocketLatency(latency) | Show round-trip time | A new measurement, about once per ping |
useAgentApproval(responder, method) | Render requests from the server that a person answers | A request arrives or goes away |
useAgentRun(runs, runId) | Render a resumable run, such as an agent's answer that survives reconnects and reloads | Every event of the run |
useAgUiAgent(agent) | Render an AG-UI agent's thread: messages, tool calls, shared state | Every event |
useWebSocketStream(rpc, options?) | Stream the replies to a request into a value, such as tokens into an answer, with Stop | Every reply, or once per frame |
useWebSocketOutbox(outbox) | List the messages waiting in an outbox | A message is added, sent or acknowledged |
useWebSocketPresence(presence) | Render the other peers' shared state, such as live cursors | A peer's state arrives, it leaves or it times out |
useInView(ref, options?) | Pick a topic by whether an element is on screen, to stream full detail only for what's visible | The element enters or leaves the viewport |
#Components
| Component | |
|---|---|
<WebSocketDevtools sources? open? position? /> | A development panel with each client's status, queue, buffer, messages, round-trip time, topics, feeds, outbox, presence and runs. From react-websocket/devtools |
#Functions
| Function | |
|---|---|
createWebSocket(url, options?) | Create a client to share across components or use outside React |
createWebSocketTopics(client, options) | Manage reference-counted topic subscriptions, resent after every reconnect |
createWebSocketFeeds(client, options) | Topic subscriptions with numbered messages: each delivered once and in order across reconnects, with resume and snapshots |
createWebSocketState(client, options) | Keep state reduced from a client's messages |
createWebSocketRequests(client, options) | Send requests and await their replies or stream them, with timeouts and cancellation |
createWebSocketLatency(client, options) | Measure round-trip time and estimate the server's clock |
createWebSocketSendRate(client, options?) | Send aim, cursor or position at a rate that adapts to the connection, coalesced per key |
createWebSocketPresence(client, options) | Share per-peer state such as cursors, throttled and refreshed, with peers that expire when they go quiet |
createWebSocketResponder(client, options) | Answer requests the server sends, in code or from the UI |
createWebSocketRuns(client, options) | Stream runs, such as an agent's answer, that resume after a reconnect or a reload, with a keep or cancel policy |
createWebSocketTimeline(client, options) | Interpolate server snapshots and predict your own inputs, for multiplayer games. From react-websocket/timeline |
createWebSocketOutbox(client, options) | Keep messages in IndexedDB until the server acknowledges them, across reconnects and reloads. From react-websocket/outbox |
createAgUiAgent(client, options?) | Run an AG-UI agent over a WebSocket, with resumable runs and JSON Patch state. From react-websocket/ag-ui |
applyAgUiEvent(thread, event) | Fold an AG-UI event into a thread. From react-websocket/ag-ui |
applyPatch(document, operations) | Apply a JSON Patch without changing the document. From react-websocket/ag-ui |
createWebTransportSocket(options?) | A WebSocket class that connects over WebTransport, with volatile sends as datagrams and a WebSocket fallback. From react-websocket/webtransport |
createTabsWebSocket(options?) | A WebSocket class that shares one connection between all the tabs of an app. From react-websocket/tabs |
createChaosWebSocket(options?) | A WebSocket class that injects network faults in development. From react-websocket/chaos |
createRecordingWebSocket(options?) | A WebSocket class that records sessions to JSON. From react-websocket/replay |
createReplayWebSocket(recording, options?) | A WebSocket class that plays a recording back without a server. From react-websocket/replay |
retryableClose(close) | The default reconnect.shouldReconnect: false for close codes 1002, 1003 and 1008. Call it from your own to keep that rule |
retryAfter(close) | The default reconnect.retryAfter: the delay in ms from a 1012 or 1013 close whose reason is a number of seconds. Call it from your own to keep reading it |
#Classes
| Class | |
|---|---|
MessageError | Reported to onError when a message fails parse or schema |
#Types
| Type | |
|---|---|
WebSocketOptions | Connection options |
UseWebSocketOptions | WebSocketOptions plus handlers and enabled |
UseWebSocketResult | What useWebSocket returns |
UseWebSocketStreamOptions | { initial, reduce, batch? } |
UseWebSocketStreamResult | { value, status, error, start, abort } from useWebSocketStream |
WebSocketHandlers | onOpen, onMessage, onClose, onError, enabled |
WebSocketClient | The client returned by createWebSocket |
Status | 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed' |
Snapshot | { status, lastMessage, attempt } |
CloseInfo | { code, reason, wasClean } |
EventMap | Events and listener signatures |
UrlSource | A URL string or a function returning one |
SendData | What WebSocket.send accepts |
SendOptions | { volatile?, key?, priority?, maxBuffered?, maxAge?, onDrop? } for send() |
ReconnectOptions | Backoff settings |
HeartbeatOptions | Keep-alive settings |
QueueOptions | Send queue limit and maximum age |
WebSocketTopics | The topic manager from createWebSocketTopics |
WebSocketTopicsOptions | { subscribe, unsubscribe? } |
WebSocketFeeds | The feeds from createWebSocketFeeds: topics plus on('message') and position() |
WebSocketFeedsOptions | { subscribe, unsubscribe?, resume?, sequence, snapshot?, onGap? } |
FeedPosition | { topic, seq } |
MessageSource | Something with the client's message event, such as feeds, for createWebSocketState |
WebSocketState | The store from createWebSocketState |
WebSocketStateOptions | { initialState, reduce, batch? } |
WebSocketRequests | The request manager from createWebSocketRequests |
WebSocketRequestsOptions | { send, reply, error?, done?, cancel?, timeout? } |
RequestOptions | { timeout?, signal?, volatile?, key?, priority?, maxBuffered? } for request() and stream() |
WebSocketLatency | The latency tracker from createWebSocketLatency |
WebSocketLatencyOptions | { ping, pong, interval?, samples? } |
Latency | { rtt, offset } |
WebSocketSendRate | The sender from createWebSocketSendRate |
WebSocketSendRateOptions | { maxRate?, minRate?, maxBuffered?, latency?, maxRttIncrease? } |
SendRate | { rate, congested } |
WebSocketPresence | The presence from createWebSocketPresence |
WebSocketPresenceOptions | { send, leave?, receive, timeout?, refresh?, maxRate? } |
PresencePeer | { peer, state, updatedAt } |
WebSocketResponder | The responder from createWebSocketResponder |
WebSocketResponderOptions | { request, respond, error, cancel?, timeout? } |
IncomingRequest | { id, method, params, signal, respond, reject } |
RequestHandler | (params, request) => result | Promise<result> for onRequest |
WebSocketRuns | The runs from createWebSocketRuns |
WebSocketRunsOptions | { name, start, resume, cancel?, event, done?, error?, initial, reduce, policy?, storage? } |
AgentRun | { runId, status, value, error } |
RunPolicy | 'keep' | 'cancel': what happens to a run when its connection drops |
RunStatus | 'streaming' | 'done' | 'error' | 'aborted' |
RunStorage | getItem, setItem and removeItem, like sessionStorage |
WebSocketTimeline | The timeline from createWebSocketTimeline |
WebSocketTimelineOptions | { snapshot, interpolate?, delay?, extrapolate?, buffer?, latency?, input? } |
TimelineSnapshot | { time, state, ack? } |
TimelineInputOptions | { send, predict, maxBuffered? } |
WebSocketOutbox | The outbox from createWebSocketOutbox |
WebSocketOutboxOptions | { name, send, ack?, maxAge?, onExpire?, storage? } |
OutboxEntry | { id, message, createdAt, sent } |
OutboxStorage | { load, put, delete }, where an outbox keeps its messages |
OutboxRecord | { id, message, createdAt }, what an outbox stores |
AgUiAgent | The agent from createAgUiAgent |
AgUiAgentOptions | { threadId?, state?, name?, run?, resume?, cancel?, resync?, event?, policy?, storage? } |
AgUiThread | { messages, state, status, step?, error?, result?, stale } |
AgUiMessage, AgUiToolCall, AgUiEvent, AgUiEnvelope, RunAgentInput, JsonPatchOperation | AG-UI's shapes, from react-websocket/ag-ui |
StandardSchemaV1 | The schema interface zod, valibot and arktype implement |
WebTransportWebSocket, WebTransportSocketOptions | From react-websocket/webtransport |
TabsWebSocket | The class from createTabsWebSocket: typeof WebSocket plus dispose() |
TabsWebSocketOptions, TabsTopics | { WebSocket?, json?, topics?, linger? } and { subscribe, unsubscribe, topic? } |
ChaosWebSocket | The class from createChaosWebSocket: typeof WebSocket plus its controls |
ChaosOptions | { WebSocket?, seed?, logger? } plus the faults |
WebSocketRecording, RecordingWebSocket, ReplayWebSocket, ReplayOptions | From react-websocket/replay |
ChaosFaults | { enabled?, latency?, loss?, refuse?, drop?, stall?, corrupt? } for configure() |
ChaosControls | configure, drop, stall and inject |
ChaosRange | A duration in ms, or [min, max] |