use-shopping-cart logouse-shopping-cart
Configuration

persistKey

This property specifies the localStorage key name used to persist the cart. By default, the cart is stored under the key 'use-shopping-cart'.

Type

string

Default

'use-shopping-cart'

Usage

import { createRoot } from 'react-dom/client'
import { CartProvider } from 'use-shopping-cart'
import App from './App'

createRoot(document.getElementById('root')).render(
  <CartProvider currency="USD" persistKey="my-custom-cart">
    <App />
  </CartProvider>
)

How It Works

The persistKey is used directly as the localStorage key:

// Default behavior
localStorage.setItem('use-shopping-cart', cartData)

// With custom persistKey
localStorage.setItem('my-custom-cart', cartData)

Common Use Cases

Multiple Cart Instances

Run multiple independent carts on the same site:

// Main shopping cart
<CartProvider persistKey="main-cart">
  <MainStore />
</CartProvider>

// Gift registry cart
<CartProvider persistKey="gift-registry">
  <GiftRegistry />
</CartProvider>

Each cart maintains its own separate localStorage entry.

Environment-Specific Keys

Use different keys for development and production:

const persistKey = process.env.NODE_ENV === 'production'
  ? 'shopping-cart'
  : 'dev-shopping-cart'

<CartProvider persistKey={persistKey}>
  <App />
</CartProvider>

Namespace by User

For multi-tenant applications:

const persistKey = `cart-${userId}`

<CartProvider key={userId} persistKey={persistKey}>
  <App />
</CartProvider>

CartProvider reads persistKey when it mounts. The key makes it start a new cart under the new persistKey when userId changes, for example after the shopper signs in; without it, the cart keeps using the first key.

Avoid Conflicts

If your app uses localStorage extensively:

<CartProvider persistKey="mystore-shopping-cart">
  <App />
</CartProvider>

Inspecting in DevTools

You can view the persisted cart data:

  1. Open browser DevTools
  2. Go to Application > Storage > Local Storage
  3. Find your key (default: 'use-shopping-cart')
  4. View the JSON cart data

Clear Specific Cart

// Clear specific cart from localStorage
localStorage.removeItem('my-custom-cart')

Notes

  • Only relevant when shouldPersist={true} (default)
  • Read once, when CartProvider mounts; change the provider's key to switch keys
  • The key is used as-is, no prefixes or transformations
  • Choose unique keys to avoid conflicts
  • Keep keys consistent to maintain cart across sessions

See Also

On this page

Shopping Cart

Your cart is empty

Try the interactive demos on the docs pages!