What you'll learn: By the end of this lesson you will be able to turn a stream of server messages into React state with one pure reducer, explain why a screen needs a snapshot plus a stream and how to join them without a race, detect a missed or repeated message with a sequence number, read a live store from components with
useSyncExternalStore, keep redraws proportional to what changed, and choose between invalidating a query, patching a query cache and keeping a separate live store.
Picture the departures board at a railway station. A train is delayed, and only that one row flips. But if the board's power flickered for a minute, nobody can tell from the board alone whether a row is current. A live screen has the same two problems: which part should move when one message arrives, and how the client knows it missed something.
The page in this lesson is a live product board on a shop: a list of products whose price and stock change as the server pushes messages. The lab's products and numbers are made up for the lesson. The transports (polling, Server-Sent Events, WebSockets) have their own lessons in this course, and the server side is in WebSockets, Server-Sent Events and Long Polling; ordinary fetched data is in Server State: Caching and Revalidation. This lesson covers the step between: a message arrives and must become state.
The core idea
- A message is an event about a stream, and the screen needs state. Keep one pure function,
applyEvent(state, event), that takes the old state and one event and returns the new state. Everything else (sockets, React, caches) is wiring around it. - A stream alone is not enough, and a snapshot alone goes stale. The client needs a snapshot (a normal request) to start from and a stream to stay current, and it needs a sequence number on every message so it can tell a gap or a repeat from the next message in line.
- Render cost is a design decision. If every message calls
setStateat the top of the page, every message redraws every row. If rows subscribe only to the product they show, and the store notifies once per batch, a message costs one row.
Three illustrations run through the lesson: a minimal example (one product's stock changing), a realistic example (the board with a snapshot, a stream and a lost message) and a failure example (a board that keeps saying "in stock" after missing a message).
From messages to state: one reducer
The board's state is a map of products by id. The lab's stream has three kinds of event: upsert (a whole product), patch (changed price or stock) and remove. Each carries two numbers that answer different questions.
| Number | Belongs to | Question it answers | Rule in the lab |
|---|---|---|---|
seq |
The whole stream | Did I miss a message, or see one twice? | seq <= lastSeq is a duplicate and is dropped. seq > lastSeq + 1 is a gap: hold the message and get a fresh snapshot. |
version |
One product | Is this change older than what I hold? | A change with a version not above the product's version is ignored, and a removed product keeps its removal version so an older upsert cannot revive it. |
applyEvent never mutates its input, and a product that did not change keeps the same object; React decides whether to redraw by comparing objects, so this matters later. It returns an outcome with the new state (applied, ignored, duplicate or gap) and leaves the decision to the caller, so it stays free of timers and sockets. The same shape fits a query cache: TanStack Query's setQueryData(queryKey, updater) calls the updater with the current data, which may be undefined, and stores what it returns. Its documentation says updates must be immutable and that an undefined result leaves the cache untouched.
Figure 1. From socket to row
How to read this: events and snapshots enter the store and components read from it. Only the store knows about order, gaps and batching.
Subscribe first, then fetch
A page needs a starting point from an ordinary request, then the stream, and the order decides whether anything is lost. Fetching first and subscribing after misses every change made in between. Subscribing first loses nothing, but messages arrive while the snapshot loads and some are already inside it. The sequence number resolves this: a snapshot that says "this is the list after event 9" lets the client drop messages 8 and 9 as duplicates and apply 10 and 11.
Figure 2. Joining a snapshot and a stream
How to read this: the client shows no half-built list. It stays "syncing" until the snapshot arrives, then replays only what the snapshot lacks.
This needs the server to number its events and say which event a snapshot follows; that contract is the lab's own design. Server-Sent Events has a built-in relative: the id field sets the event source's last event ID, and the user agent sends it in a Last-Event-ID header when it reconnects (WHATWG HTML Standard). With a WebSocket the application defines its own numbering, as the lab does.
When a message is missed
Networks lose and reorder messages, and servers restart. The store keeps three states, and moving between them is what keeps the screen honest.
Figure 3. The store's status
How to read this: "stale" is a visible state, not an error. The old rows stay on screen with a status line, a snapshot is requested once, and a late message can close the gap without one.
Two details are easy to get wrong. A gap must hold later messages: applying seq 14 while 13 is missing shows a state the server never had. And the snapshot request must go out once per period of being behind, not once per held message. The demo shows a lost 13 leaving "status stale, held 2, snapshot requests 1", and a snapshot at 15 returning the store to live. The held list needs a limit too: the lab's store gives up waiting when it holds too many.
Getting it into React
React's useSyncExternalStore(subscribe, getSnapshot) reads a store that lives outside React. Per the React documentation, subscribe takes a callback and returns a cleanup function; when the store calls the callback, React calls getSnapshot again and redraws the component if the value is different as compared by Object.is. While the store has not changed, repeated calls to getSnapshot must return the same value, and the snapshot must be immutable. A subscribe function that changes identity on a re-render makes React resubscribe, so the lab's is a stable property of the store. Server rendering needs the optional getServerSnapshot.
Because redraws follow object identity, the granularity of the selector sets the cost:
// from src/react.tsx: a row reads one product, so it redraws only when that product's object changes
export function useLiveItem(store: LiveStore, id: string): Product | undefined {
return useSyncExternalStore(store.subscribe, () => store.getItem(id), () => store.getItem(id));
}
The list reads getIds, which returns the same array until the set of products changes, so a price change does not redraw the container. Both guarantees come from the reducer keeping the old object for anything it did not change.
| Approach | State lives | One message for one product redraws | Cost to get right |
|---|---|---|---|
useState at the top of the page |
Page component | Every row (unless each row is memoized) | Lowest; fine for a handful of rows and rare messages |
| Store plus a selector per row | External store | One row | A store with stable getters |
Query cache patched with setQueryData |
Query cache | The components that read that query | Keys and updaters to maintain |
React's Profiler calls onRender whenever a component in the profiled tree commits an update. The lab wraps each row in one to count commits per row; React disables profiling in production builds by default, so this is a development and test tool.
Batching: one notification per frame
A WebSocket message event fires whenever data is received, so a busy feed can deliver many in a second, and calling React for each multiplies work. The store only queues in receive and schedules one flush, which applies everything queued and notifies once. The scheduler is injected: a microtask, an animation frame, or a manual one in tests.
requestAnimationFrame calls a function before the next repaint, generally at the display's refresh rate, and MDN notes it is paused in most browsers in background tabs. A frame-based scheduler therefore needs a plan for a hidden tab: a limit on the queue, a timer fallback, or a resync on return. The lab does not implement one; it is a stretch exercise.
The demo feeds the same 300 messages for 5 products two ways. Flushing after every message gives 300 notifications and 300 row redraws; flushing once per frame of 5 messages gives 60 notifications and 195 row redraws, with an identical final state. A list that redraws every row on each notification would do 1,500.
Patch, invalidate or keep a store
When a message arrives, an app that already uses a query cache has three choices.
Figure 4. What to do with an incoming message
to compute the new value?"} Q1 -->|"no, it only says 'changed'"| INV["Invalidate the query and refetch"] Q1 -->|"yes"| Q2{"Frequent messages and
many components read pieces?"} Q2 -->|"no"| PATCH["Patch the query cache with a reducer"] Q2 -->|"yes"| STORE["Keep a live store, per-item subscriptions"]
How to read this: invalidating is simplest but costs a request per message. Patching saves the request and needs ordering rules.
Per the TanStack Query documentation, invalidateQueries marks matching queries as invalidated and, unless refetchType is 'none', refetches them: a request per invalidation, which suits a message that only says "something changed". Patching with setQueryData avoids the request but takes on ordering, duplicates and gaps. The library's defaults help a little: cached data is stale and refetched in the background on mount, window focus and reconnect, and structural sharing keeps the same reference for unchanged data. A patched cache still needs a snapshot refetch as its recovery path.
Build it: a live store and a thin React layer
Goal. Run the store through six situations without React, then see React tests count redraws for the store-based and the naive board.
Setup. The lab is examples/frontend/labs/realtime-react-state in the course's example workspace (Node 26.13.1, React 19.3.1, Vitest 5.1.0, jsdom). The core is pure TypeScript; React and Testing Library are used only for the thin layer's tests.
cd examples/frontend
pnpm install
cd labs/realtime-react-state
pnpm test # 31 tests
node src/demo.ts
Steps. Run the tests and the demo. In section 1 find "duplicates dropped 2, applied 2" (the snapshot already held events 8 and 9). In section 3 a late message turns the status from stale back to live with no snapshot. In section 5 compare 300 notifications with 60 for the same final stock.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01):
=== 1. Subscribe first, fetch second: events 8 to 11 arrive while the snapshot (taken after event 9) is still loading
status syncing, events held 4, a: (not loaded)
snapshot loaded: status live, last seq 11, a: stock 110, v11
events 8 and 9 were already inside the snapshot: duplicates dropped 2, applied 2
=== 2. A message is lost: seq 13 never arrives
status stale (last known data still shown: a: stock 100, v12), held 2, snapshot requests 1 (gap)
snapshot at seq 15 loaded: status live, a: stock 60, v15, held 0
=== 3. The missing message was only late
after seq 14: status stale, a: stock 100, v12, snapshot requests 1
after seq 13 arrives: status live, a: stock 70, v14, applied 2
=== 4. Repeats and old versions
sent seq 1 twice and then a change with version 4 (older than v6): a: stock 99, v6
applied 1, duplicates 1, ignored 1
=== 5. 300 events for 5 products in 60 frames of 5: one notification per message, or one per frame
flush after every message: 300 events applied, 300 notifications, 300 row redraws (a list that redraws every row on each notification: 1500)
flush once per frame : 300 events applied, 60 notifications, 195 row redraws (a list that redraws every row on each notification: 300)
final stock, same in both runs: 32, 30, 61, 66, 92
=== 6. A resync keeps the object of every product that did not change
resync at seq 5, only b changed (v4 to v5): row redraws {"a":0,"b":1}
The React tests check the same idea on components: an event for one product commits one row of the store-based board and all three rows of a naive useState board, and 20 messages flushed together commit a row once, against 20 times when flushed one by one.
What the lab does not show. No browser, socket or real timing: the React tests run in jsdom, the test hands messages to the store, and the "frame" is a scheduler the test runs by hand. It does not use TanStack Query, so that advice rests on its documentation. It does not model a hidden tab, Strict Mode, transitions or a server render. The event shapes, the seq and version rules and the status names are the lab's own design, not a protocol or a library's behaviour.
Break it. In src/events.ts, delete the line that returns duplicate for seq <= state.lastSeq. Repeated messages are now applied, and three tests fail (the two duplicate tests and the 200 seeded sessions). Restore it.
In practice: a flash-sale board that kept saying "in stock"
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A shop runs a flash sale on a page of about 200 products. Price and stock change as orders arrive, and the server pushes the changes over a WebSocket. The page fetches the list once and puts every pushed message into a top-level useState.
Starting architecture
Figure 5. Starting point: every message goes through the top of the page
How to read this: nothing checks message order, and nothing limits how many redraws one burst causes.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Invalidate the list query on every message | Always correct, no ordering rules | A request per message in a burst | The API carries the sale's load |
| Reducer with numbered events and a refetch on a gap, in a live store with per-row subscriptions | No extra requests; one row redraws per change | Server must number events; a reducer to test | Two sources of data if the query cache also holds the list |
The decision
| Field | Decision record |
|---|---|
| Context | Messages are frequent, only a few rows change at a time, and a stale "in stock" costs money. |
| Decision | Number every event on the server and put the sequence number in the snapshot. Reduce events in a pure function. Flush once per frame. Rows subscribe to one product. On a gap, show a status line and refetch the snapshot once. |
| Consequences, good | A burst costs a few row redraws, and a missed message is noticed and repaired. |
| Consequences, bad | The server and the client now share a numbering contract that must be versioned with the API. |
| Revisit when | Messages become rare (invalidation is simpler) or the list is needed by many unrelated screens (move it into the query cache). |
Rollout and verification
- Add
seqto the stream and the snapshot first; the old client ignores it. - Ship the store behind a flag and compare its rows with a fresh fetch on a sample of sessions.
- Count gaps detected, snapshots requested, duplicates dropped and time spent stale.
The 2 a.m. failure
During the sale the socket gateway is restarted. Some messages are lost, and the page that had no gap detection keeps showing "in stock" for products that sold out, because nothing tells it that messages are missing (illustrative). Shoppers add sold-out items to their cart and checkout fails.
First three checks: (1) compare the page's stock for one product with a fresh fetch; (2) check whether the stream numbers its events and whether the client compares them; (3) check whether the page notices a reconnect and fetches again. Mitigation: refetch the snapshot on every reconnect and show a status line while syncing. Follow-up: add sequence numbers, gap detection and a "stale" status, and alert on the share of sessions that spend more than a few seconds stale.
Architect's notes
- Reduce, don't set. Order, duplicates and tests become properties of one function.
- Make "behind" visible. A board that says it is stale beats a wrong one that looks current.
- Keep a recovery path that does not depend on the stream. A snapshot request makes every other failure survivable.
- Treat the numbering as an API, and version it like one.
Common mistakes
- Fetching first and subscribing second, so changes in between are lost.
- Applying a message after a gap.
- Returning a new object from
getSnapshoton every call. - One
setStateper message on a busy feed. - A snapshot request per held message, which turns an outage into a request storm.
Key takeaways
- Put one pure reducer between events and state.
- Use a snapshot plus a stream, joined by a sequence number, and subscribe before you fetch.
- Detect duplicates and gaps, hold what is early, ask for a snapshot once.
useSyncExternalStoreredraws on a different object: keep unchanged objects identical.- Batch: queue messages, notify once per frame.
- Invalidate for "changed", patch when the message carries data, use a live store for hot data.
Practice exercises
Exercise 1 — Starter (45 min): Add a rename event to the reducer with tests for a duplicate, an older version and an unknown product.
Exercise 2 — Intermediate (2 hours): Add a scheduler that uses requestAnimationFrame, with a timer when the document is hidden, and test it with a fake clock.
Exercise 3 — Advanced (half day): Wrap applyEvent as an updater (old) => new and keep a live store and a query cache in step. List every place they can disagree (refetch, optimistic update, gap) and decide who wins.
Related reading
In this course:
- Server State: Caching and Revalidation, the cache a snapshot refetch refreshes.
- WebSockets, Server-Sent Events and Long Polling, the server side of the stream and how each transport resumes.
- State Persistence and Synchronization, another place where ordering is not merging.
- Optimistic Updates and Rollback, when a local change and a pushed change meet.
Official documentation
- React: useSyncExternalStore, the arguments, the
Object.iscomparison and the snapshot rules. - React: Profiler, commit measurements and the production default.
- TanStack Query: QueryClient,
setQueryData,invalidateQueriesandcancelQueries. - TanStack Query: Important Defaults, staleness, background refetch and structural sharing.
- MDN: requestAnimationFrame() and WebSocket: message event.
- WHATWG HTML Standard: Server-sent events, the
idfield and theLast-Event-IDheader.