createWebSocketLatency
Measure round-trip time and estimate the server's clock with application-level pings.
Available from both react-websocket and react-websocket/core.
Usage
Your server answers each ping with its id and its own Date.now():
Read the measurements in components with useWebSocketLatency. The guide is Real-time games. For a countdown every screen agrees on, see Build a multiplayer party game.
Parameters
Returns
WebSocketLatency:
Latency
Both are undefined until the first pong. offset stays undefined if pongs carry no time.
Behavior
- Pings while open. The first ping goes out as soon as the socket opens, before messages queued while disconnected. After that, one goes out every
interval. Pings pause while not open, and they are sent withvolatile, so they're never queued. They ignore backpressure: on a congested link they wait in the send buffer like everything else, sorttshows the congestion. - Smoothing.
rttis the median of the lastsamplesround trips, so one slow ping doesn't make it jump.offsetcomes from the sample with the lowest round trip, the most accurate estimate. It assumes the server read its clock halfway through the round trip. - Reconnects. Samples from the previous connection are discarded when a new one opens. The last values stay readable until a new pong arrives.
- Doesn't connect. It starts measuring whenever the client is open, but doesn't hold the connection.
useWebSocketLatencydoes. - Pongs are messages. Pongs also reach
onMessage,lastMessageand state stores. WithuseWebSocket, that's one extra render per interval. - Not a heartbeat. It doesn't detect dead connections. Use the
heartbeatoption for that. Both can run on the same client. - Requires TypeScript 5.4+ for the inferred message types (it uses
NoInfer).