Frontend components refactoring #2: the batch store
Getting out of the tree. How a module-level batch store lets components that don't know each other share one request, without a container above them.
Previously
In the last episode we watched the three-layer structure come into being: pure logic in core, React hooks in hooks, UI components on top. (The packages have since settled into their final names: @commercelayer/core-components and @commercelayer/react-hooks-components.)
I closed it with a specific promise: a story about how a Map, a Set and a setTimeout killed hundreds of API calls.
It's a good line. It's also false. And it's worth starting there, because why it's false is more interesting than the line.
The story that doesn't hold up
Here's the easy version. Catalog page, twenty products, twenty <Price> components:
<Price skuCode="TSHIRTMM000000FFFFFFXLXX" />
<Price skuCode="TSHIRTMM000000FFFFFFLXXX" />
{/* ...and eighteen more */}
Each component knows only its own skuCode and has no idea its siblings exist. Twenty self-contained components, twenty HTTP requests, twenty round trips for data the API would return in one call with a single filter. Then the batch store arrives and one remains. Twenty to one. Headline written.
Except those twenty requests never happened. The old PricesContainer already batched, with the exact same fifty-millisecond debounce:
const fetchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
const codes = contextSkuCodes?.length > 0 ? contextSkuCodes : skuCodes
if (config.accessToken != null && codes.length > 0) {
if (fetchTimerRef.current != null) clearTimeout(fetchTimerRef.current)
fetchTimerRef.current = setTimeout(() => {
fetchPrices({ filters: { sku_code_in: codes.join(",") }, pageSize: perPage })
}, 50)
}
return () => {
if (fetchTimerRef.current != null) clearTimeout(fetchTimerRef.current)
clearPrices()
}
}, [config.accessToken, skuCodes, contextSkuCodes, filtersKey, perPage])
One request, same sku_code_in filter, same debounce window. The refactoring did not eliminate a single call that was actually being made.
So what did it fix?
The real problem: coordination cost you a node in the tree
The answer isn't how many requests fire. It's where the code has to live for only one to fire.
In the old model, coordination lived in a component. PricesContainer accumulated codes in a useState, started the timer, distributed results through context. It worked, and it carried three consequences.
- The implicit contract
<Price>only worked inside<PricesContainer>. Outside: silence, or a runtime error. The compiler had nothing to say, because the contract lived inside auseContext— invisible in the component's signature, invisible to the types, discoverable only by getting it wrong. - Context only flows down
This is the structural limit, and the serious one. If two<Price>components sit in sibling subtrees — one in the header, one in the product grid, one in the mini cart — there is no container close enough to coordinate them without wrapping half the application. And if you wrap everything in one giant container, you've tied the fetch lifecycle to that node's lifecycle: when it unmounts, it takes everyone's cache with it. - Duplication
SkusContainerhad its own copy of the same idea. Different timer, differentuseState, subtly different cleanup. Same logic, two implementations, two sets of potential bugs. A third domain would have made three.
None of these three is about request count. They're all the same question: where does the state that coordinates components who don't know each other actually live?
The insight: get out of the tree
Coordination between sibling components isn't a React problem. It's a module-level shared state problem.
React knows nothing about which prices the page needs. But the JavaScript module that imports usePrices is singular, shared by every instance of the hook. If the state lives there, outside the component tree, position in the DOM stops mattering.
That's createBatchStore.
Anatomy of createBatchStore
It's a factory. It returns an independent store with four public functions and zero React imports:
type StoreEntry = {
/** Registered codes, with the number of consumers currently holding each one. */
codes: Map<string, number>
timer: ReturnType<typeof setTimeout> | null
/** Immutable snapshot consumed by `useSyncExternalStore`. */
snapshot: readonly string[]
listeners: Set<() => void>
}
export function createBatchStore() {
const store = new Map<string, StoreEntry>()
// ...
return { subscribe, getSnapshot, registerCode, unregisterCode, EMPTY }
}
The Map, keyed by accessToken. Not a detail — it's the isolation boundary. Two different sessions, an authenticated user and a guest, or two markets in the same app, must never land in the same batch. The key guarantees one session's codes never contaminate another's fetch.
The Map of codes. Several components asking for the same code produce one entry, which is what keeps the filter that ends up in the query compact. But the entry isn't a plain set member: it carries a counter. Why becomes clear once those components start unmounting, and it's the subtlest decision in the file.
The timer. The heart of the batching:
function scheduleFlush(entry: StoreEntry): void {
if (entry.timer != null) clearTimeout(entry.timer)
entry.timer = setTimeout(() => {
entry.snapshot = Object.freeze(Array.from(entry.codes.keys()))
entry.timer = null
for (const listener of entry.listeners) listener()
}, 50)
}
Every new registration cancels the previous timer and schedules a fresh one. A classic debounce: as long as components keep mounting, the flush slides forward. When the stream goes quiet for fifty milliseconds, the snapshot is produced once and every subscriber is notified.
The snapshot. There are two distinct things here that are easy to conflate — and that I conflated in the first draft of this episode.
The snapshot is stored on entry.snapshot and rebuilt only on flush. That is what satisfies the useSyncExternalStore contract: getSnapshot must return the same reference until the state genuinely changes. Build a fresh array on every call and React spins into an infinite render loop — and it would do so with a frozen array too, because freezing doesn't make a reference stable.
Object.freeze answers a different question: stopping a consumer from mutating the shared array from outside. Good defensive practice, not the mechanism that makes the hook work.
The Set of listeners. The list of interested components, and the garbage collection mechanism.
The bridge to React
The store is pure TypeScript. React notices through the hook React 18 introduced for exactly this, inside usePrices:
const stableSubscribe = useCallback(
(listener: () => void) => subscribe(accessToken, listener),
[accessToken]
)
const stableSnapshot = useCallback(() => getSnapshot(accessToken), [accessToken])
const skuCodesList = useSyncExternalStore(
stableSubscribe,
stableSnapshot,
() => EMPTY // server snapshot: nothing to batch during SSR
)
How to subscribe, how to read current state, what to return during server rendering. React handles the rest — including correctness under concurrent rendering, which is the whole reason this hook exists and why a hand-rolled event emitter plus useEffect is not equivalent.
The double net: debounce + SWR
It's worth showing the key here, because the whole mechanism rests on it:
const { data, error, isLoading, isValidating, mutate } = useSWR<Price[]>(
shouldFetch && accessToken
? batchCodes != null
? ["prices", "batch", accessToken, batchCodes]
: ["prices", "get", accessToken, fetchParams]
: null,
async (): Promise<Price[]> =>
batchCodes != null
? fetchInChunks(batchCodes, (codes, pageSize) =>
getPrices({
accessToken,
params: { filters: { sku_code_in: codes.join(",") }, pageSize },
interceptors,
})
)
: getPrices({ accessToken, params: fetchParams, interceptors }),
{ revalidateOnFocus: false, revalidateOnReconnect: false }
)
Two keys, not one. ["prices", "batch", …] when the codes come from the store, ["prices", "get", …] when someone called fetchPrices by hand: two ways of asking for prices that shouldn't share a cache entry. Either way it's a declarative key, not an imperative trigger, and that's what makes the deduplication real.
Every usePrices instance sharing an accessToken receives the same snapshot, so produces the same batchCodes, so the same key. And SWR, faced with twenty instances asking for that key in the same instant, fires a single fetch. The other nineteen attach to the same promise.
Two complementary layers: the debounce decides what to ask for, collapsing twenty codes into one filter; SWR decides how many times to ask.
Why fifty milliseconds and not a microtask
DataLoader is the obvious prior art here, and that comparison obliges an explanation.
DataLoader batches per tick: it collects everything requested in the same turn of the event loop and then fires. Here the window is fifty milliseconds, which is far longer.
Components mounting in the same commit run their effects in the same commit, so a setTimeout(0) — or a microtask — would batch them just as well. The wider window isn't for them: it's for staggered mounts. A <Price> inside a Suspense boundary that resolves a few milliseconds later, a list hydrating progressively, a tab mounting its children on first render — with per-tick batching those land in separate requests. Fifty milliseconds collects them together.
It's a trade: you pay that latency on every first paint in exchange for a tighter batch when rendering isn't instantaneous. A chosen number, not an obvious one.
The subtle decisions
unregisterCode does not trigger a refetch.
function unregisterCode(accessToken: string, code: string): void {
const entry = store.get(accessToken)
if (entry == null) return
const count = entry.codes.get(code)
if (count == null) return
if (count > 1) entry.codes.set(code, count - 1)
else entry.codes.delete(code)
}
No scheduleFlush, no notification. When a <Price> unmounts, removing its code must not invalidate cached data for everyone else. An unmount is never a good reason to redo a network call.
And a code leaves the batch only with its last consumer. This is where it becomes clear why the Map carries a counter instead of being a Set. The same SKU often appears in several places on a page — the grid card, a modal, the mini cart — and each of those components registers and unregisters on its own. With a plain set, the first to unmount would take the code away from the others too, which are still mounted and reading that data; the next flush would omit it from the snapshot and those components would lose their price. The counter settles it in two lines:
function registerCode(accessToken: string, code: string): void {
if (!accessToken) return
const entry = getOrCreate(accessToken)
const count = entry.codes.get(code) ?? 0
entry.codes.set(code, count + 1)
if (count > 0) return
scheduleFlush(entry)
}
With one detail worth noting: if the counter was already above zero the function returns without scheduling a flush. Registering a code that's already there doesn't change the set of codes to ask for, so there's nothing to renegotiate — and the siblings' debounce isn't postponed for nothing.
Cleanup lives in the unsubscribe.
return () => {
entry.listeners.delete(listener)
if (entry.listeners.size === 0) {
if (entry.timer != null) clearTimeout(entry.timer)
store.delete(accessToken)
}
}
A module-level store is by definition a potential memory leak: it lives as long as the page. The listener count acts as a reference counter — when the last component interested in that token unmounts, the entry disappears and any pending timer is cleared. No orphan timers firing into a dead store.
The empty-token guard. One line, if (!accessToken) return, stopping a component mounted before auth is ready from creating a ghost entry keyed on the empty string — a batch shared across sessions, precisely what keying by token was meant to prevent.
What the design carries with it
Every architectural choice has a cost, and it's worth naming.
The flush is cumulative. The snapshot is rebuilt from the full set, so every flush after the first contains every code registered so far. A late-mounting <Price> — infinite scroll, a tab, a resolving Suspense boundary — produces a new key and puts the whole batch back in play, not just its own code. That's the price of one shared snapshot instead of one request per component.
One request per twenty-five codes. The Commerce Layer API accepts at most twenty-five records per page, and a list request returns a single page. A wider batch would be silently truncated, so it doesn't go out as is: fetchInChunks splits it into chunks of twenty-five, fires them in parallel with Promise.all and concatenates the results.
const chunks: string[][] = []
for (let i = 0; i < codes.length; i += BATCH_PAGE_SIZE) {
chunks.push(codes.slice(i, i + BATCH_PAGE_SIZE))
}
const responses = await Promise.all(chunks.map((chunk) => fetchChunk(chunk, BATCH_PAGE_SIZE)))
For the twenty products in the example it's still one request. Above twenty-five it becomes two, then three, and the honest promise is no longer "one request" but "one request per twenty-five codes" — which, combined with the cumulative flush, means a late mount replays every chunk, not just the new one. There's also a case the chunks don't cover, because it doesn't depend on the number of codes: one SKU can have several prices, so twenty-five codes can return more than twenty-five records. There the truncation would be invisible, so it is said out loud:
if ("meta" in response && response.meta.pageCount > 1) {
console.warn(
`[createBatchStore] a batch request returned ${response.meta.recordCount} records but only the first ${BATCH_PAGE_SIZE} were loaded.`
)
}
Module state and SSR. A module-level store in a server-rendered app immediately raises the spectre of sessions bleeding into each other. It doesn't arise here, for a structural reason: registration happens inside useEffect, and effects never run on the server. getServerSnapshot always returns EMPTY, so server rendering produces the loading state and batching begins after hydration, in the browser.
Where the premise does crack is elsewhere: if a bundle ends up containing two copies of the package — micro-frontends, duplicate versions, a badly resolved workspace — each brings its own module, hence its own store. Components served by the two copies don't coordinate, and batching degrades into two requests instead of one. Not a bug: the price of module-level state, and worth knowing.
Reuse: eight lines per domain
Here the architectural payoff is real. pricesBatchStore.ts, in full:
import { EMPTY as _EMPTY, createBatchStore } from "@commercelayer/core-components"
const _store = createBatchStore()
export const EMPTY: readonly string[] = _EMPTY
export const subscribe = _store.subscribe
export const getSnapshot = _store.getSnapshot
export const registerSku = _store.registerCode
export const unregisterSku = _store.unregisterCode
And skusBatchStore.ts is identical line for line, apart from the header comment.
Two fully independent stores — separate instances, separate Maps, separate timers — created with one line of code each. Behavior is guaranteed identical because it is the same code: a change to createBatchStore lands everywhere, at the same moment, with the same semantics. Adding batching to a third domain costs eight lines.
What changes for library users
This is the visible result, and the episode's real headline: the container disappears from user code.
// Before — mandatory, and every <Price> under the same node
<PricesContainer>
<Price skuCode="SKU-A" />
<Price skuCode="SKU-B" />
</PricesContainer>
// Now — anywhere, including subtrees that never meet
<Price skuCode="SKU-A" /> // in the header
<Price skuCode="SKU-B" /> // in the grid
Inside Price, standalone mode is detected with one elegant tell: if setSkuCodes from context is undefined, there's no container above, and the component delegates everything to the hook.
const isStandalone = setSkuCodes == null
useEffect(() => {
if (!isStandalone || !sCode) return
registerSku(sCode)
return () => unregisterSku(sCode)
}, [isStandalone, sCode, registerSku, unregisterSku])
Register on mount, unregister on unmount. Four lines. Everything else — coordination, debouncing, deduplication, cleanup — is solved elsewhere, once.
And the old PricesContainer? Not deleted: it became a usePrices consumer like every other, marked @deprecated, warning in development. Existing code keeps working; anyone who wants to migrate, can.
The lesson
The pattern hiding in this episode is bigger than batching, and it isn't new — worth saying, because pretending otherwise would weaken the argument rather than strengthen it.
For years the React answer to "these components need to coordinate" has been: lift state up. Find a common ancestor, put the state there, pass it down. It works until the common ancestor is the application root, or until the state's lifecycle no longer matches any node's.
The alternative — state in a module, useSyncExternalStore as the bridge — is exactly what Zustand, Redux and TanStack Query do. useSyncExternalStore exists in React 18 because those libraries needed it. createBatchStore invents nothing: it applies a known pattern to a specific problem, in seventy lines instead of a dependency.
And that's the part that counts:
Component position stops being an architectural constraint, and as a side effect the logic becomes pure, testable and reusable — because it never needed React to be correct in the first place.
The previous episode closed by saying the best architecture is the one that makes change cheap. This is the practical proof: seventy lines of TypeScript that import nothing at runtime, with tests that run in milliseconds, in place of coordination logic spread across two React components, two contexts and two lifecycles. It isn't only more correct. It's easier to change next time.