What You'll Learn
- 1Model a socket connection as explicit statuses instead of a boolean connected flag
- 2Reconnect with exponential backoff and jitter while respecting React cleanup and Strict Mode
- 3Decode frames defensively and keep message ordering and duplicates under control
- 4Decide when a socket is justified and what the fallback should be when it fails
Opening a socket is one line of code. Keeping a socket honest for the life of a browser session is where the engineering happens: the laptop lid closes, the network switches from wifi to a tether, a proxy times out an idle connection, a deploy restarts the server, and React itself mounts your component twice in development before settling. A component that treats the socket as a fire-and-forget effect works in the demo and then quietly stops updating, with the UI still showing a green dot because nothing ever set it back to false. Real-time features are less about pushing bytes than about representing connection state, message order and recovery in code a reviewer can verify.
Treat the connection as a state machine
The first design decision is the shape of the state you expose. A single isConnected boolean cannot express the difference between the initial attempt, a healthy stream, a connection that dropped and is retrying, and one that has failed permanently. Those four states look identical to a status badge and completely different to the rest of the application: a reconnecting socket should queue or drop outgoing messages, a failed socket should surface a retry button, and a healthy one should be invisible.
Expose a status string plus a send function, and keep the socket itself in a ref so that changing handlers does not tear down the connection. Handler functions passed as props change on every render, and an effect that depends on them would reconnect on every keystroke of the parent. Storing the latest callback in a ref that the event listener reads is the standard way to break that dependency while still letting the listener call current code.
A hook that reconnects instead of giving up
Backoff is not decoration. A server restart that takes fifteen seconds will knock out every client at the same moment, and clients that retry after a fixed one-second interval produce a thundering herd that extends the outage. Exponential growth with a cap and a random jitter spreads the retries so the server recovers against a trickle rather than a spike.
import { useCallback, useEffect, useRef, useState } from 'react';
export function useWebSocket(url, onMessage) {
const [status, setStatus] = useState('connecting');
const socketRef = useRef(null);
const timerRef = useRef(null);
const attemptRef = useRef(0);
const onMessageRef = useRef(onMessage);
onMessageRef.current = onMessage;
const connect = useCallback(() => {
clearTimeout(timerRef.current);
const socket = new WebSocket(url);
socketRef.current = socket;
socket.addEventListener('open', () => {
attemptRef.current = 0;
setStatus('connected');
});
socket.addEventListener('message', (event) => {
let frame;
try {
frame = JSON.parse(event.data);
} catch (error) {
console.error('Dropping malformed frame', error);
return;
}
onMessageRef.current(frame);
});
socket.addEventListener('close', () => {
if (socketRef.current !== socket) return;
setStatus('disconnected');
const attempt = attemptRef.current++;
const ceiling = Math.min(1000 * 2 ** attempt, 15000);
const delay = ceiling + Math.random() * 500;
timerRef.current = setTimeout(connect, delay);
});
socket.addEventListener('error', () => socket.close());
}, [url]);
useEffect(() => {
connect();
return () => {
clearTimeout(timerRef.current);
const socket = socketRef.current;
socketRef.current = null;
socket.close();
};
}, [connect]);
const send = useCallback((payload) => {
const socket = socketRef.current;
if (!socket || socket.readyState !== WebSocket.OPEN) return false;
socket.send(JSON.stringify(payload));
return true;
}, []);
return { status, send };
}
The guard inside close matters more than the timer. Without comparing the closing socket to the current ref, a stale socket from a previous effect run can schedule a second connection while the new one is still opening, and the application ends up with two live sockets both delivering messages. The same guard pattern is what makes the hook survive React Strict Mode, where the effect runs, cleans up and runs again in development.
Decode frames as if the server might be wrong
Network code fails at the boundaries. A reverse proxy can serve an HTML error page on the socket route, an intermediary can inject a keep-alive string, and a rolling deploy can briefly send a frame from an older schema. Parsing must therefore be total: wrap the decoder, discard anything unexpected, and never let one bad frame throw inside the event handler, because a throw there is invisible in your component tree and kills nothing except the message you wanted.
Give every frame an explicit envelope with a type and a sequence number. Consumers then switch on type rather than sniffing at payload shape, and the sequence number gives you two things for free: duplicate detection after a reconnect, and an ordering check that reveals a gap you should repair with a fetch rather than silently render.
import { useCallback, useEffect, useRef } from 'react';
const TYPES = new Set(['chat', 'presence', 'inventory']);
export function useOrderedFeed(url, onBatch, requestReplay) {
const lastSeqRef = useRef(0);
const bufferRef = useRef([]);
const handleFrame = useCallback(
(frame) => {
if (!TYPES.has(frame.type) || typeof frame.seq !== 'number') return;
if (frame.seq <= lastSeqRef.current) return;
bufferRef.current.push(frame);
bufferRef.current.sort((a, b) => a.seq - b.seq);
const ready = [];
while (
bufferRef.current.length &&
bufferRef.current[0].seq === lastSeqRef.current + 1
) {
ready.push(bufferRef.current.shift());
lastSeqRef.current += 1;
}
if (ready.length) onBatch(ready);
if (bufferRef.current.length > 50) {
requestReplay(lastSeqRef.current + 1);
bufferRef.current = [];
}
},
[onBatch, requestReplay]
);
useEffect(() => {
lastSeqRef.current = 0;
bufferRef.current = [];
}, [url]);
return handleFrame;
}
The gap branch is the important one. If sequence four never arrives, rendering five through nine anyway leaves a hole in the conversation that no amount of correct rendering will fix; requesting a replay since the last sequence you handled is cheap insurance and turns an ordering bug into a logged retry.
Keeping the server authoritative
A socket delivers events, not truth. Clients that treat incoming frames as the whole picture drift the moment two of them disagree, and a user who reconnects with a stale view will send commands based on data the server has already changed. The reliable pattern is to apply events to a local cache, then reconcile with the server on every reconnect using a resume token or a last-seen sequence.
| Approach | What the client holds | Recovery after a drop | Cost |
|---|---|---|---|
| Apply frames only | Whatever arrived | Nothing; gaps stay forever | Cheapest, most drift |
| Replay since a cursor | Full log from the cursor | Replays missed frames | Needs server-side retention |
| Refetch snapshot on connect | Current truth, then live deltas | Snapshot repairs every gap | One extra request per reconnect |
| Server-driven resync signal | Marked invalid on mismatch | Client asks for a full refresh | Simplest correct option |
Snapshot plus deltas is the default worth reaching for. The socket stays a fast path for updates while a single query on open restores correctness, which means a lost frame costs one request instead of a data-integrity incident.
Heartbeats, backpressure and idle connections
Idle sockets die quietly. Proxies and load balancers drop connections with no traffic after a few minutes, and the browser does not always report the close promptly, so the interface believes it is connected long after the link is gone. A heartbeat every thirty seconds both keeps the path warm and gives you a liveness signal: if two heartbeats go unanswered, close the socket yourself and let the backoff logic reconnect rather than waiting for a timeout you do not control.
Outbound traffic needs the same discipline. Sending on every keystroke of a collaborative editor produces frames the server has no hope of applying in order at full speed, so batch on an animation frame or a short interval, coalesce updates to the same key, and watch the buffered amount the socket reports. When the buffer grows past a threshold the connection is effectively stalled, and it is better to drop intermediate frames for a slider than to queue a thousand positions that are all obsolete.
Also listen for the browser going offline and for the tab becoming visible again. A backgrounded tab throttles timers, so reconnection backoff stretches, and on return the first thing to do is verify the connection rather than assume it survived.
Choosing between sockets, server-sent events and polling
WebSockets are bidirectional, which matters when the client sends as often as it receives: cursors, votes, game input. When traffic is one-way, server-sent events are dramatically simpler â automatic reconnection, plain HTTP, no framing to design â and the client can post to a normal endpoint when it needs to respond. Polling remains the right answer for low-value updates behind a proxy you do not control, and it is the fallback your interface should degrade to when the socket cannot be opened at all.
The practical rule is to keep a fallback path visible in the product rather than hidden in the code. A status that says updates are delayed with a refresh button is a better experience than a dot that claims everything is live while the page has been frozen for ten minutes.
Common Mistakes
Depending on message handlers in the effect so the socket reconnects whenever a parent re-renders
Fix: Keep the socket in a ref and read the latest callback from a ref the listener consults
Parsing frames without a try and catch so one proxy error page breaks the stream
Fix: Treat decoding as fallible, discard unknown frames, and log rather than throw
Assuming a connected status means messages are still arriving
Fix: Heartbeat on a timer and force a reconnect when responses stop
Building the entire UI state from incoming frames with no reconciliation
Fix: Refetch a snapshot or replay from a cursor whenever the connection is re-established
Best Practices
- Model connecting, connected, disconnected and failed as distinct states with different UI
- Cap backoff and add jitter so a server restart does not produce a retry storm
- Give every frame a type and a sequence number and buffer until the sequence is contiguous
- Heartbeat every thirty seconds and close proactively when replies stop
- Provide a polling or refresh fallback for networks where the upgrade never completes
Key Takeaways
- A socket hook must survive double mounting, stale closures and silent proxy timeouts, not just the happy path
- Exponential backoff with jitter turns a coordinated client stampede into a recoverable trickle
- Defensive decoding and sequence numbers convert silent corruption into logged, repairable gaps
- Server state stays authoritative: sockets deliver deltas, snapshots restore truth
- Heartbeats and buffered-amount checks are what tell you the connection is genuinely alive