Skip to main content

useCart

The useCart hook provides access to the cart object. It must be a descendent of a CartProvider component.

Example code

import {CartProvider, useCart} from '@shopify/hydrogen';

export function MyComponent() {
return (
<CartProvider>
<CartLineItems />
</CartProvider>
);
}

export function CartLineItems() {
const {lines} = useCart();

return (
<>
{lines.map((line) => {
return {
/* your JSX*/
};
})}
</>
);
}

Return value

The useCart hook returns an object with the following keys:

NameDescription
idThe cart ID.
linesThe cart lines.
checkoutUrlThe URL for the checkout for this cart.
noteThe cart note.
buyerIdentityThe cart's buyer identity.
attributesThe cart attributes.
discountCodesThe discount codes applied to the cart.
costThe cost for the cart, including the subtotal, total, taxes, and duties.
statusThe status of the cart. This returns 'uninitialized' when the cart is not yet created, 'creating' when the cart is being created, 'updating' when the cart is updating, and 'idle' when the cart isn't being created or updated.
errorA string of an error from a cart action, such as adding or removing an item from the cart. If an error does occur, then the cart is put back into the last valid state it was in.
cartCreateA callback that creates a cart. Expects the same input you would provide to the Storefront API's cartCreate mutation.
linesAddA callback that adds lines to the cart. Expects the same lines input that you would provide to the Storefront API's cartLinesAdd mutation. If a cart doesn't already exist, then it will create the cart for you.
linesRemoveA callback that removes lines from the cart. Expects the same lines input that you would provide to the Storefront API's cartLinesRemove mutation. Only lines that are included in the lines parameter will be in the cart afterwards.
linesUpdateA callback that updates lines in the cart. Expects the same lines input that you would provide to the Storefront API's cartLinesUpdate mutation. If a line item is not included in the lines parameter, it will still exist in the cart and will not be changed.
noteUpdateA callback that updates the note in the cart. Expects the same note input that you would provide to the Storefront API's cartNoteUpdate mutation.
buyerIdentityUpdateA callback that updates the buyer identity in the cart. Expects the same buyerIdentity input that you would provide to the Storefront API's cartBuyerIdentityUpdate mutation.
cartAttributesUpdateA callback that updates the cart attributes. Expects the same attributes input that you would provide to the Storefront API's cartAttributesUpdate mutation.
discountCodesUpdateA callback that updates the cart's discount codes. Expects the same codes input that you would provide to the Storefront API's cartDiscountCodesUpdate mutation.
totalQuantityThe total number of items in the cart, across all lines. If there are no lines, then the value is 0.