Skip to content

fix(hydrogen): call cart selector hook unconditionally in useOptionalCart#3845

Open
malewis5 wants to merge 3 commits into
Shopify:previewfrom
vercel-labs:mttlws/use-optional-cart-fix
Open

fix(hydrogen): call cart selector hook unconditionally in useOptionalCart#3845
malewis5 wants to merge 3 commits into
Shopify:previewfrom
vercel-labs:mttlws/use-optional-cart-fix

Conversation

@malewis5

@malewis5 malewis5 commented Jul 8, 2026

Copy link
Copy Markdown

WHY are these changes introduced?

useOptionalCart called the useCartSelector hook after an early
return undefined when rendered outside a <CartProvider>. That makes a
hook run conditionally, violating the Rules of Hooks: the number/order of
hooks changes between renders depending on whether a provider is present,
which can corrupt React's hook state and crash in dev.

WHAT is this pull request doing?

  • useOptionalCart now always calls useCartSelector, passing a
    possibly-null store instead of returning early.
  • useCartSelector accepts CartStore | null: getSnapshot returns
    undefined when there's no store, and it subscribes via a no-op
    subscribe so useRef/useSyncExternalStore always run in the same
    order.
  • useCart continues to cast the result with as S, preserving the
    non-optional return type; useOptionalCart returns S | undefined.

No behavioral change for consumers inside a provider.

HOW to test your changes?

From packages/hydrogen:

pnpm test        # vitest — src/react/cart.test.tsx (26/26 passing)
pnpm typecheck

@malewis5
malewis5 requested a review from a team as a code owner July 8, 2026 18:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant