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:
| Key | Value (type) | Required |
|---|---|---|
name | Name of the product to be shown on the Checkout page (string) | Yes |
description | description to be shown on the Stripe Checkout page (string) | No |
id | A unique identifier for this item (string) | Yes |
price | Price in smallest currency unit (number) | Yes |
currency | ISO currency code (string) | Yes |
image | Image to be shown on the Stripe Checkout page (string) | No |
price_id | Price id provided by Stripe | No |
sku_id | SKU id provided by Stripe (Supports Deprecated API) | No |
sku | A unique identifier for this item (string) | No |
price_data | Optional params for Price API for Serverless integrations | No |
product_data | Optional params for Price API for Serverless integrations | No |
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:
skuandidare interchangeable for backwards compatibility, butidis preferred (SKU API is deprecated by Stripe) - The product must include at minimum:
id,name,price, andcurrency countmust 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
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.
