use-shopping-cart logouse-shopping-cart

Getting Started

Get up and running with use-shopping-cart in minutes.

Installation

npm install use-shopping-cart@rc

# or
yarn add use-shopping-cart@rc

# or
pnpm add use-shopping-cart@rc

Requirements

  • React 19+
  • A Stripe account (for creating Checkout Sessions on your server)

Basic Setup

1. Wrap your app with CartProvider

import { CartProvider } from 'use-shopping-cart'

function App() {
  return (
    <CartProvider currency="USD">
      <YourApp />
    </CartProvider>
  )
}

2. Add products to your cart

import { useShoppingCart } from 'use-shopping-cart'

function ProductCard() {
  const { addItem } = useShoppingCart()

  const product = {
    id: 'banana_001',
    name: 'Bananas',
    price: 400, // $4.00 in cents
    currency: 'USD',
    image:
      'https://images.unsplash.com/photo-1571771894821-ce9b6c11b08e?w=400&h=400&fit=crop&q=80'
  }

  return (
    <div>
      <h3>{product.name}</h3>
      <p>${product.price / 100}</p>
      <button onClick={() => addItem(product)}>Add to Cart</button>
    </div>
  )
}

3. Display cart contents

import { useShoppingCart } from 'use-shopping-cart'

function Cart() {
  const {
    cartCount,
    formattedTotalPrice,
    cartDetails,
    incrementItem,
    decrementItem,
    removeItem
  } = useShoppingCart()

  if (cartCount === 0) {
    return <p>Your cart is empty</p>
  }

  return (
    <div>
      <h2>Cart ({cartCount} items)</h2>

      {Object.entries(cartDetails).map(([id, item]) => (
        <div key={id}>
          <h4>{item.name}</h4>
          <p>
            {item.formattedPrice} × {item.quantity}
          </p>

          <button onClick={() => decrementItem(id)}>-</button>
          <span>{item.quantity}</span>
          <button onClick={() => incrementItem(id)}>+</button>

          <button onClick={() => removeItem(id)}>Remove</button>
        </div>
      ))}

      <h3>Total: {formattedTotalPrice}</h3>
    </div>
  )
}

4. Create a server endpoint for checkout

Create an API endpoint that creates a Stripe checkout session. Never price the session from the cartDetails the browser sends, because anyone can edit it. Pass it to validateCartItems with your own product list, which takes prices from your inventory:

// pages/api/create-checkout-session.js (Next.js)
import Stripe from 'stripe'
import { validateCartItems } from 'use-shopping-cart/utilities'
import { inventory } from '../../data/products'

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)

export default async function handler(req, res) {
  try {
    const { cartDetails } = req.body
    const line_items = validateCartItems(inventory, cartDetails)

    const session = await stripe.checkout.sessions.create({
      mode: 'payment',
      line_items,
      success_url: `${req.headers.origin}/success`,
      cancel_url: req.headers.origin
    })

    res.json({ sessionUrl: session.url })
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
}

inventory is the same list of products you add to the cart, loaded somewhere the browser can't change it: a file on the server, a database or your product API.

5. Redirect to checkout

import { redirectToCheckout, useShoppingCart } from 'use-shopping-cart'

function CheckoutButton() {
  const cartDetails = useShoppingCart((cart) => cart.cartDetails)

  const handleCheckout = async () => {
    // Call your server to create a session
    const response = await fetch('/api/create-checkout-session', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cartDetails })
    })

    const { sessionUrl } = await response.json()

    // Redirect to Stripe checkout
    redirectToCheckout(sessionUrl)
  }

  return <button onClick={handleCheckout}>Checkout</button>
}

That's It!

Your shopping cart is now fully functional. The cart automatically persists to localStorage and works across page refreshes.

Next Steps

On this page

Shopping Cart

Your cart is empty

Try the interactive demos on the docs pages!