API reference

Everything the package exports. All exports are typed, and every type has inline documentation that your editor shows on hover.

Entry points

ImportContentsNotes
react-websocketHooks, createWebSocket, MessageError, typesMarked 'use client' for Server Components frameworks
react-websocket/corecreateWebSocket, the other create* functions, MessageError, typesNo React dependency. Use it in workers, Node, or other frameworks
react-websocket/timelinecreateWebSocketTimeline, its typesFor multiplayer games. No React dependency
react-websocket/ag-uicreateAgUiAgent, applyAgUiEvent, applyPatch, their typesAG-UI agents over a WebSocket. No React dependency
react-websocket/outboxcreateWebSocketOutbox, indexedDBStorage, memoryStorage, their typesMessages kept until acknowledged, across reloads. No React dependency
react-websocket/webtransportcreateWebTransportSocket, its typesWebTransport behind the same API, with a WebSocket fallback. No React dependency
react-websocket/tabscreateTabsWebSocket, its typesOne connection shared by every tab. No React dependency
react-websocket/devtoolsWebSocketDevtools, its propsA development panel showing every client. Marked 'use client'
react-websocket/replaycreateRecordingWebSocket, createReplayWebSocket, their typesRecord sessions and replay them without a server. No React dependency
react-websocket/chaoscreateChaosWebSocket, its typesA development tool. No React dependency

Every entry point ships as ESM and CommonJS with type declarations for each.

Hooks

HookUse it toRe-renders on
useWebSocket(url | client, options?)Connect and read status and the latest messageStatus changes and every message
useWebSocketEvent(client, type, listener)Handle events without re-renderingNever
useWebSocketStatus(client)Show connection statusStatus changes only
useWebSocketTopic(topics, topic)Hold topic subscriptions that survive reconnectsNever
useWebSocketState(store, selector?, isEqual?)Read state reduced from messagesThe selected value changes
useWebSocketLatency(latency)Show round-trip timeA new measurement, about once per ping
useAgentApproval(responder, method)Render requests from the server that a person answersA request arrives or goes away
useAgentRun(runs, runId)Render a resumable run, such as an agent's answer that survives reconnects and reloadsEvery event of the run
useAgUiAgent(agent)Render an AG-UI agent's thread: messages, tool calls, shared stateEvery event
useWebSocketStream(rpc, options?)Stream the replies to a request into a value, such as tokens into an answer, with StopEvery reply, or once per frame
useWebSocketOutbox(outbox)List the messages waiting in an outboxA message is added, sent or acknowledged
useWebSocketPresence(presence)Render the other peers' shared state, such as live cursorsA 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 visibleThe 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
MessageErrorReported to onError when a message fails parse or schema

Types

Type
WebSocketOptionsConnection options
UseWebSocketOptionsWebSocketOptions plus handlers and enabled
UseWebSocketResultWhat useWebSocket returns
UseWebSocketStreamOptions{ initial, reduce, batch? }
UseWebSocketStreamResult{ value, status, error, start, abort } from useWebSocketStream
WebSocketHandlersonOpen, onMessage, onClose, onError, enabled
WebSocketClientThe client returned by createWebSocket
Status'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed'
Snapshot{ status, lastMessage, attempt }
CloseInfo{ code, reason, wasClean }
EventMapEvents and listener signatures
UrlSourceA URL string or a function returning one
SendDataWhat WebSocket.send accepts
SendOptions{ volatile?, key?, priority?, maxBuffered?, maxAge?, onDrop? } for send()
ReconnectOptionsBackoff settings
HeartbeatOptionsKeep-alive settings
QueueOptionsSend queue limit and maximum age
WebSocketTopicsThe topic manager from createWebSocketTopics
WebSocketTopicsOptions{ subscribe, unsubscribe? }
WebSocketFeedsThe feeds from createWebSocketFeeds: topics plus on('message') and position()
WebSocketFeedsOptions{ subscribe, unsubscribe?, resume?, sequence, snapshot?, onGap? }
FeedPosition{ topic, seq }
MessageSourceSomething with the client's message event, such as feeds, for createWebSocketState
WebSocketStateThe store from createWebSocketState
WebSocketStateOptions{ initialState, reduce, batch? }
WebSocketRequestsThe request manager from createWebSocketRequests
WebSocketRequestsOptions{ send, reply, error?, done?, cancel?, timeout? }
RequestOptions{ timeout?, signal?, volatile?, key?, priority?, maxBuffered? } for request() and stream()
WebSocketLatencyThe latency tracker from createWebSocketLatency
WebSocketLatencyOptions{ ping, pong, interval?, samples? }
Latency{ rtt, offset }
WebSocketSendRateThe sender from createWebSocketSendRate
WebSocketSendRateOptions{ maxRate?, minRate?, maxBuffered?, latency?, maxRttIncrease? }
SendRate{ rate, congested }
WebSocketPresenceThe presence from createWebSocketPresence
WebSocketPresenceOptions{ send, leave?, receive, timeout?, refresh?, maxRate? }
PresencePeer{ peer, state, updatedAt }
WebSocketResponderThe responder from createWebSocketResponder
WebSocketResponderOptions{ request, respond, error, cancel?, timeout? }
IncomingRequest{ id, method, params, signal, respond, reject }
RequestHandler(params, request) => result | Promise<result> for onRequest
WebSocketRunsThe 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'
RunStoragegetItem, setItem and removeItem, like sessionStorage
WebSocketTimelineThe timeline from createWebSocketTimeline
WebSocketTimelineOptions{ snapshot, interpolate?, delay?, extrapolate?, buffer?, latency?, input? }
TimelineSnapshot{ time, state, ack? }
TimelineInputOptions{ send, predict, maxBuffered? }
WebSocketOutboxThe 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
AgUiAgentThe 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, JsonPatchOperationAG-UI's shapes, from react-websocket/ag-ui
StandardSchemaV1The schema interface zod, valibot and arktype implement
WebTransportWebSocket, WebTransportSocketOptionsFrom react-websocket/webtransport
TabsWebSocketThe class from createTabsWebSocket: typeof WebSocket plus dispose()
TabsWebSocketOptions, TabsTopics{ WebSocket?, json?, topics?, linger? } and { subscribe, unsubscribe, topic? }
ChaosWebSocketThe class from createChaosWebSocket: typeof WebSocket plus its controls
ChaosOptions{ WebSocket?, seed?, logger? } plus the faults
WebSocketRecording, RecordingWebSocket, ReplayWebSocket, ReplayOptionsFrom react-websocket/replay
ChaosFaults{ enabled?, latency?, loss?, refuse?, drop?, stall?, corrupt? } for configure()
ChaosControlsconfigure, drop, stall and inject
ChaosRangeA duration in ms, or [min, max]