Free

State Management · E-commerce · React

Client store, server cart, auth token, persisted localStorage and multiple tabs — a shopping cart has all the hard problems of distributed state. How to make synchronization explicit instead of hoping the last write wins.
November 29, 2026·10 min read·By Abhay Chauhan (Full Stack Developer)

Your Cart Is a Distributed System (And That's Why It Desyncs)

#State Management#E-commerce#React#Reliability#Zustand#Distributed Systems
The short answer: A cart that lives in a client store, a server API, localStorage and multiple tabs is a distributed system, and it suffers the same problems: stale reads, conflicting writes and lost updates. The fix is to make synchronization explicit — rebase client state from server responses at defined points, store the cart token with the data, listen for cross-tab storage events and rehydrate, and reconcile variations by identity rather than index.

The bug reports all sounded different: "my cart emptied after login," "I added two variants but see one line," "the other tab still shows the old cart." They were the same bug wearing different clothes — a state machine with four copies and no agreed authority.


1. Four copies of one truth

A typical cart has:

  • A client store (Zustand or similar) driving the UI.
  • A server cart (WooCommerce or a custom API) holding the real line items.
  • A persisted copy in localStorage for reload survival.
  • An auth token that changes the server's view of the cart when the user logs in.

Every copy can be correct at one instant and wrong the next. Without explicit synchronization, the last write wins — and "last" is not well defined across tabs and network delays.


2. Rebase on the server response

Mutations should be optimistic for responsiveness, but they must be followed by a reconciliation step: replace local state with the server's authoritative response. Otherwise a quantity clamp, a coupon rejection or a stock limit applied server-side is invisible to the UI.

ts
const serverCart = await updateCartAction(lineItems);
setCart(reconcile(localCart, serverCart)); // derive from truth

The important shift is from "apply my change and hope" to "apply my change, then converge on what the server says."


3. Variations must be matched by identity

A recurring source of duplicate or merged lines is matching on product ID alone. Two variations of the same product are different lines. Reconciliation must match on full identity — product plus variation attributes — and merge by quantity only for exact matches.

This is a data-modeling rule, not a UI detail: if your cart item type cannot express variation identity, every later fix will be a patch on a broken foundation.


4. Cross-tab sync is not automatic

Each tab has its own in-memory store. localStorage is shared, but a tab does not re-read it just because another tab wrote it. Listen for storage events and rehydrate:

ts
if (typeof window !== 'undefined') {
  window.addEventListener('storage', (e) => {
    if (e.key === 'cart-storage') useCartStore.persist.rehydrate();
  });
}

Now a change in one tab propagates to the others. Without this, the "two tabs disagree" report is inevitable.


5. Persist only what matters

State stores accumulate transient flags: loading, open/closed drawers, error messages. Persisting all of them means a reload can restore a stale error or a stuck spinner. Use partialize to persist only the cart items and the cart token:

ts
persist(
  (set, get) => ({ ...state }),
  {
    name: 'cart-storage',
    partialize: (state) => ({
      items: state.items,
      cartToken: state.cartToken,
    }),
  }
)

The token must be persisted with the items: a cart without its token is a cart the server cannot identify.


6. Auth transitions are synchronization points

Login and logout change the server's view of the cart. These are explicit synchronization points: refetch the server cart and replace local state after the auth state changes. Treating them as ordinary background events is how carts appear to "empty after login."


7. Defense in depth

ProblemNaive approachExplicit sync
Server clamps quantityLocal optimistic value sticksRebase on server response
Two tabsEach keeps own stateStorage event + rehydrate
VariationsMatch by product IDMatch by full identity
ReloadRestores transient UI statePersist only items + token
LoginCart seems to emptyRefetch at auth transition

How to fix cart desync

  1. Define which copy of the cart is authoritative at each point.
  2. Rebase local state on server responses after every mutation.
  3. Match line items by product plus variation identity.
  4. Listen for storage events and rehydrate across tabs.
  5. Persist only items and token; refetch on auth transitions.

Frequently asked questions

Is the server or the client authoritative? The server, for anything that affects price, stock or orders. The client is an optimistic projection of it.

Do storage events fire in the same tab? No — they fire in other tabs of the same origin. Same-tab updates must go through the store directly.

Should I persist the whole store? No. Persist data, not UI state. Use partialize.

What about offline support? Offline queues need their own versioning and conflict resolution; start with explicit server rebasing before adding offline complexity.


Key takeaways

  • Carts are distributed state; treat them that way.
  • Rebase on the server after mutations.
  • Match variations by full identity.
  • Sync tabs via storage events and rehydration.
  • Persist only items and token; refetch on auth changes.

Summary

Most cart bugs are not UI bugs — they are consistency bugs. Once you name the authority and define the synchronization points, the mysterious desyncs become deterministic behavior you can reason about.


References

  • Zustand documentation — persist middleware and partialize.
  • MDN Web Docs — StorageEvent.
  • React documentation — useSyncExternalStore.

Got something you're building?