use-shopping-cart logouse-shopping-cart

addItem()

To add a product to the cart, use useShoppingCart()'s addItem(product) method. It takes in your product object which must be in the following shape:

KeyValue (type)Required
nameName of the product to be shown on the Checkout page (string)Yes
descriptiondescription to be shown on the Stripe Checkout page (string)No
id A unique identifier for this item (string)Yes
pricePrice in smallest currency unit (number)Yes
currencyISO currency code (string)Yes
imageImage to be shown on the Stripe Checkout page (string)No
price_idPrice id provided by StripeNo
sku_id SKU id provided by Stripe (Supports Deprecated API)No
skuA unique identifier for this item (string)No
price_dataOptional params for Price API for Serverless integrationsNo
product_dataOptional params for Price API for Serverless integrationsNo
const products = [
  {
    name: 'Bananas',
    description: 'Yummy yellow fruit',
    id: 'id_banana001',
    price: 400,
    currency: 'USD',
    image:
      'https://images.unsplash.com/photo-1571771894821-ce9b6c11b08e?w=400&h=400&fit=crop&q=80'
  }
]

Basic Usage

import { useShoppingCart } from 'use-shopping-cart'
import type { Product } from 'use-shopping-cart/core'

function ProductCard({ product }: { product: Product }) {
  const { addItem } = useShoppingCart()

  return (
    <div className="product-card">
      <img src={product.image} alt={product.name} />
      <h3>{product.name}</h3>
      <p>${product.price / 100}</p>

      <button onClick={() => addItem(product)}>Add to Cart</button>
    </div>
  )
}

Adding with Custom Quantity

You can add multiple items at once by passing a count option (positive integers only):

// Add 10 items at once
addItem(product, { count: 10 })

Adding with Metadata

Stripe allows you to attach custom metadata to products and prices. This metadata will be passed through to your Stripe Checkout session and webhooks:

addItem(product, {
  count: 1,
  product_metadata: {
    category: 'fruit',
    seasonal: 'true'
  },
  price_metadata: {
    discount_applied: 'summer-sale',
    original_price: '5.99'
  }
})

See the metadata example for a complete implementation.

Notes

  • SKU vs ID: sku and id are interchangeable for backwards compatibility, but id is preferred (SKU API is deprecated by Stripe)
  • The product must include at minimum: id, name, price, and currency
  • count must be a positive integer
  • Metadata is optional and useful for tracking, analytics, or custom business logic

Interactive Demo

Cart Display

Total Items: 0

Cart is empty. Add items to see them here!

Bananas product photo

Bananas

Yummy yellow fruit

$4.00

Try it out:

Try adding items above! The cart state persists across all documentation pages, so you can navigate to other action pages and see the same cart.

Shopping Cart

Your cart is empty

Try the interactive demos on the docs pages!