A real-time React dashboard that keeps up with WebSockets
Why a live dashboard slows down over time, and the fixes: render once per frame, cap the list, aggregate as events arrive, and plan for reconnects.
By M. Adnan Saleem · · Updated · 7 min read
For a vehicle cybersecurity platform I engineered real-time threat detection dashboards in React and TypeScript on WebSocket feeds, which cut analyst time-to-insight by about 20%. A live dashboard has one job that a normal page does not: it must stay responsive while data keeps arriving, for hours. The feed demo below shows the same state handling on a simulated feed.
What goes wrong first
The obvious version works in a demo and falls over in production:
socket.onmessage = (message) => {
// One render per message, and a list that grows for as long as the tab is open
setEvents((prev) => [JSON.parse(message.data), ...prev]);
};It has two faults. Every message triggers a render, so a burst of fifty messages is fifty renders in a row. And the list never stops growing, so memory and render time climb all day until the tab is reloaded.
Render per frame, not per message
The screen updates about sixty times a second, so rendering more often than that is wasted work. Collect incoming messages in a buffer and flush it once per animation frame:
useEffect(() => {
const socket = new WebSocket(url);
const buffer = [];
let frame = 0;
const flush = () => {
frame = 0;
const batch = buffer.splice(0).reverse(); // newest first
setEvents((prev) => [...batch, ...prev].slice(0, 40)); // keep what the screen can show
};
socket.onmessage = (message) => {
buffer.push(JSON.parse(message.data));
if (!frame) frame = requestAnimationFrame(flush); // at most one render per frame
};
return () => {
socket.close();
cancelAnimationFrame(frame);
};
}, [url]);A burst of any size now costs one render. The cleanup function matters as much as the handler: without it, every remount leaves a socket open behind it.
The hidden-tab trap
Browsers stop calling requestAnimationFrame while a tab is in the background, but the socket keeps receiving. With the code above, a dashboard left in another tab over lunch buffers every message until someone looks at it again, then tries to process them all at once. Cap the buffer the same way as the list:
socket.onmessage = (message) => {
buffer.push(JSON.parse(message.data));
if (buffer.length > 40) buffer.shift(); // the buffer is capped too
if (!frame) frame = requestAnimationFrame(flush);
};Counters that must stay exact should be updated in the message handler, not in the flush, so they stay correct while nothing is being drawn.
Keep only what the screen can show
An analyst reads the latest few dozen events, not the last ten thousand. Cap the list (the demo keeps 40) and leave history to the server, which can page through it on request.
When analysts do need a long history on screen, render it with windowing so only the visible rows exist in the page. Rendering 20,000 rows in React without freezing the page shows how, with the measurements.
Aggregate as events arrive
Totals and charts should not be recalculated from the list, because the list is capped and recounting is slow. Update them incrementally:
// Counters grow by one per event; no need to recount the list
setCounts((prev) => ({ ...prev, [event.level]: prev[event.level] + 1 }));
// One bucket per second for the chart: add to the newest, drop the oldest every second
setHistory((prev) => [...prev.slice(0, -1), prev[prev.length - 1] + 1]);
setInterval(() => setHistory((prev) => [...prev.slice(1), 0]), 1000);The chart then draws thirty numbers, whatever the event rate.
Plan for the connection dropping
- Reconnect with backoff. Wait one second, then two, then four, up to a ceiling, so a server restart is not met by every client at once.
- Show the state. A dashboard that silently stopped updating is worse than one that says it is reconnecting.
- Catch up. After reconnecting, ask the server for what was missed, using the last event id you saw.
Put together, the reconnect logic is short:
let attempt = 0;
let lastId = null;
let timer = 0;
function connect() {
const socket = new WebSocket(lastId ? `${url}?after=${lastId}` : url);
socket.onopen = () => { attempt = 0; };
socket.onmessage = (message) => {
const event = JSON.parse(message.data);
lastId = event.id;
receive(event);
};
socket.onclose = () => {
const ceiling = Math.min(30000, 1000 * 2 ** attempt++); // 1s, 2s, 4s ... up to 30s
timer = setTimeout(connect, ceiling / 2 + Math.random() * (ceiling / 2));
};
}The random part of the delay matters. Without it, every client that lost the connection at the same moment comes back at the same moment, and the restarted server is hit by all of them together.
Notice a connection that died quietly
A connection can stop delivering without closing: a laptop wakes from sleep, a proxy drops an idle connection, a phone changes network. The browser may not fire onclose for a long time. Have the server send a small heartbeat message every few seconds, and if the client has received nothing for two or three intervals, close the socket yourself and let the reconnect logic take over.
Do not trust the feed
One malformed message should not stop the dashboard. Wrap the parse in a try block, check that the fields you rely on are present, and drop anything that fails while counting how often it happens. Treat text from the feed as text: render it through React as usual and never as HTML.
Put together: a useLiveFeed hook
Every piece above fits in one custom hook: a render per frame, a capped buffer and list, reconnects with backoff and jitter, a catch-up id, a heartbeat timeout and a guard against malformed messages. Components then read two values and nothing else:
export function useLiveFeed(url, { limit = 40, heartbeatMs = 10000 } = {}) {
const [events, setEvents] = useState([]);
const [status, setStatus] = useState('connecting');
useEffect(() => {
const buffer = [];
let socket;
let attempt = 0;
let lastId = null;
let frame = 0;
let retryTimer = 0;
let silenceTimer = 0;
let stopped = false;
const flush = () => {
frame = 0;
const batch = buffer.splice(0).reverse();
setEvents((prev) => [...batch, ...prev].slice(0, limit));
};
const reconnect = () => {
clearTimeout(silenceTimer);
if (stopped) return;
setStatus('reconnecting');
const ceiling = Math.min(30000, 1000 * 2 ** attempt++);
retryTimer = setTimeout(connect, ceiling / 2 + Math.random() * (ceiling / 2));
};
// Nothing heard for three heartbeats: drop the socket without waiting for onclose
const watchSilence = () => {
clearTimeout(silenceTimer);
silenceTimer = setTimeout(() => {
socket.onclose = null;
socket.close();
reconnect();
}, heartbeatMs * 3);
};
function connect() {
socket = new WebSocket(lastId ? `${url}?after=${lastId}` : url);
watchSilence();
socket.onopen = () => {
attempt = 0;
setStatus('live');
};
socket.onmessage = (message) => {
watchSilence();
let event;
try {
event = JSON.parse(message.data);
} catch {
return; // count these in real code
}
if (event.type === 'heartbeat' || !event.id) return;
lastId = event.id;
buffer.push(event);
if (buffer.length > limit) buffer.shift();
if (!frame) frame = requestAnimationFrame(flush);
};
socket.onclose = reconnect;
}
connect();
return () => {
stopped = true;
clearTimeout(retryTimer);
clearTimeout(silenceTimer);
cancelAnimationFrame(frame);
socket.onclose = null;
socket.close();
};
}, [url, limit, heartbeatMs]);
return { events, status };
}When the silence timer fires, the hook removes its onclose handler before closing and reconnects straight away. A connection that died quietly can take a long time to report that it closed, which is the situation the timer exists for. The cleanup does the same, so unmounting never schedules a reconnect.
function ThreatFeed() {
const { events, status } = useLiveFeed('wss://example.com/feed');
return (
<>
<p role="status">{status === 'live' ? 'Live' : 'Reconnecting'}</p>
<ul role="log">
{events.map((event) => (
<li key={event.id}>{event.level}: {event.message}</li>
))}
</ul>
</>
);
}role="status" lets screen readers announce a lost connection, and role="log" announces new events without interrupting. Counters and chart buckets from the aggregation section belong inside onmessage, next to buffer.push, so they stay exact while the tab is hidden.
WebSocket or Server-Sent Events?
If data only flows from the server to the browser, Server-Sent Events are worth a look before a WebSocket. They run over ordinary HTTP, reconnect on their own, and resend the last event id for you through the Last-Event-ID header. Choose a WebSocket when the browser also needs to send messages on the same connection, or when the payload is binary.
Give the user control
- Pause. Nobody can read a row that keeps moving. A pause button holds the view while events keep buffering.
- Announce politely. Mark the event list with
role="log"so screen readers announce new entries without interrupting. - Make severity more than colour. Pair each colour with a word, so the meaning survives for colour-blind users and in print.
How to tell it holds
Raise the event rate well past what production sends and leave the page open. Frame rate should stay steady and memory should level off, not climb. If either drifts, something is still growing without a cap.
Live demo
Try it live
A simulated feed: raise the rate and watch the counters, chart and log stay in step. All five demos.
- 0
- high
- 0
- medium
- 0
- low
Waiting for the first event…
Simulated events, generated in your browser. Nothing here is real vehicle data.
Quick answers
The short version
Why does a React dashboard get slower over time?
Usually because a list in state grows for as long as the tab stays open, so every render has more to do, and because each incoming message triggers its own render.
How often should a live dashboard re-render?
At most once per animation frame, which is about sixty times a second. Buffer incoming messages and flush them together.
WebSocket or Server-Sent Events for a dashboard?
Server-Sent Events are simpler when data only flows from server to browser, and they reconnect on their own. Use a WebSocket when the browser also sends messages, or when you need binary data.
How do I reconnect a WebSocket safely?
Retry with a delay that doubles up to a ceiling, add some randomness so clients do not all return at once, and after reconnecting ask the server for the events you missed.
How do I detect a WebSocket connection that died without closing?
Have the server send a small heartbeat every few seconds. If the client hears nothing for two or three intervals, drop the socket and reconnect yourself, because the browser may not fire onclose for a long time.
Should a live dashboard keep every event in React state?
No. Keep the few dozen events the screen shows, update counters and chart buckets as events arrive, and leave the full history to the server to page through.
Keep reading
Related articles
- A React custom hooks library a team will actually useWhich hooks belong in a shared React library, useSyncExternalStore for browser state, useEffectEvent for stale closures, and testing hooks with renderHook.
- Redux Toolkit, Zustand or Context: where React state belongsServer state, shared client state, local UI state and URL state each have a natural home. When to use TanStack Query, Redux Toolkit, Zustand or Context.
- Rendering 20,000 rows in React without freezing the pageA reproducible React virtualization benchmark with 20,000 synthetic rows, raw runs, median filter delays, fixed-height windowing code and measurement limits.
The project behind this
Read the case study
What I built, where, and the numbers that came out of it.
Related experience: Frontend developer.