Skip to main content

Cart components

The createCartComponents function creates a cart provider, React hooks, and Vue composables typed to the cart fields that your cart server handlers return. Use the function to provide the cart to your app, read the cart, build cart forms, and refresh the cart after your own cart mutations.

In frameworks without a Hydrogen binding, use createCartStore.

Import createCartComponents from @shopify/hydrogen/react or @shopify/hydrogen/vue.


Anchor to Typed cart componentsTyped cart components

Anchor to createCartComponents
createCartComponents()

Returns a cart provider and cart hooks typed to the cart fragment in your cart server handlers. Pass typeof cartServerHandlers as the THandlers type argument. Every hook's cart state then includes your custom cart fields.

On mount, the provider sends cart requests to /api/cart and connects the store. Every hook except useOptionalCart throws when you call it outside the provider.

< <THandlers> >

The cart provider, the cart state hooks, and the cart actions and form hooks.

Examples

React

import { createCartComponents } from "@shopify/hydrogen/react";

import type { cartHandlers } from "./cart-handlers";

export const { CartProvider, useCart, useSuspenseCart, useCartActions, useCartForm } =
createCartComponents<typeof cartHandlers>();

  • In Vue, createCartComponents returns the same bindings except useSuspenseCart.
  • The useCart and useOptionalCart composables return read-only shallow refs. Call useCart without a selector to get the whole cart state.
  • The useCartForm composable also returns isPending, which tells you when the cart loads or a line updates. Call attachQuantityInput on a quantity input to submit the form when a customer changes the quantity.

Was this page helpful?