createWebSocketState
Keep state built from a client's messages with a reducer.
Available from both react-websocket and react-websocket/core.
Usage
Read it in components with useWebSocketState. The guide is Message state.
Parameters
Returns
WebSocketState<S>:
Behavior
- Listening. It listens to
'message'events from creation, and keeps state across reconnects. - Connection. It doesn't open or hold the connection;
useWebSocketStateholds it while mounted. - Notifications. Subscribers are notified only when the state changes, by
Object.is. - Batching. With
batch: 'frame', messages are still reduced as they arrive, sogetState()is always current, but subscribers hear about it once per animation frame, and not at all if the state is back where it was.setStateandresetnotify right away, including any changes still waiting for the frame. WithoutrequestAnimationFrame(Node, some workers), it waits about 16 ms instead. - Background tabs. Browsers pause animation frames in background tabs. A batched store keeps reducing, and subscribers hear about the latest state when the tab is visible again. If something must update while hidden (say,
document.title), use an unbatched store or amessagelistener for it. - Errors. A reducer that throws leaves the state unchanged; the error is re-thrown asynchronously.