We've been reworking the cart of a client's Next.js 16 food-ordering storefront, as design concepts on a staging branch. None of it is in production. Before the rework the add button waited for the server. With Slow 4G emulation that basket POST took 580-1220 ms, though the API itself answers an add in 10-18 ms. After the first add the page then fetched the whole basket again.
On the branch every basket write is a TanStack Query mutation. They all share one mutation scope, so they run one after another and an older answer can't land on top of a newer one. Each answer goes into the cache with setQueryData before the basket id cookie changes, and with a 10-second staleTime the query on the new key takes that basket as fresh. No second GET.
The cart badge adds pieces sent and not yet answered, which it reads with useMutationState filtered to status: "pending". Added lines and every total still come from the server's answer. Piece counts are optimistic; money never is.
The add buttons now react in their onSubmit, as soon as the request goes out. In one variant that took the visible response to a tap from 587-626 ms to 5-28 ms. That was a dev build on localhost, as is the trace below. We haven't measured a production build.
Then we put a DOM MutationObserver on the badge and did a first add to an empty cart on Slow 4G:
"" -> "1" at 36 ms
"1" -> "2" at 834 ms
"2" -> "1" at 865 ms
By 834 ms the answer was in the cache and the new line was counted. The add was still pending, though. TanStack keeps a mutation pending until its onSuccess and onSettled have run, so for those 31 ms the same piece was counted twice: once in the cached lines, once as a pending add.
The fix is a marker per add, kept in the mutation context:
onMutate: () => ({ answered: false }),
onSuccess: (basket, _variants, context) => {
if (context) context.answered = true;
qc.setQueryData(basketKey(basket.encoded_id), basket);
setBasketId(basket.encoded_id);
},
The badge skips answered adds. It reads the flag at render, not inside useMutationState's select, because that select only re-runs on mutation cache events and flipping a field on the context object isn't one. What re-renders the badge is the setQueryData call, through the basket query.
The trace above is from before the fix. We haven't taken a new one, and no test covers it yet.
If your badge sums cached lines and pending mutations, watch it during a first add on a throttled network and see whether it ever reads 2.