Migrating to v4.0
Guide for upgrading from v3.x to v4.0.
Overview
Version 4.0 brings significant improvements. Cart methods and state work as before, but some APIs changed (see Breaking Changes). The main changes include:
- Redux Removal: Now uses React's native
useSyncExternalStore - Modern Stripe Features: Phone collection, promotion codes, automatic tax, etc.
- React 19 Support: Full compatibility with React 19
- Client-Only Mode Removed: use checkout sessions created on your server
- Standalone
redirectToCheckout: import it and passsession.url; no Stripe key in the browser - Typed Errors: every error is a
CartErrorwith acode - Improved TypeScript: Better type inference and exported types
- Smaller Bundle: no Redux; the React entry is about 8 KB gzipped
Quick Start
Installation
npm install use-shopping-cart@rc
# or
yarn add use-shopping-cart@rc
# or
pnpm add use-shopping-cart@rcDependencies
React 19 is now required:
npm install react@19 react-dom@19Breaking Changes
Client-Only Mode Removed
Breaking: cartMode="client-only" is no longer supported. You must use checkout-session mode with a server endpoint.
Node.js 22+ Required
The package now declares "engines": { "node": ">=22" }. This applies to the Node.js version that runs your build and your server (where you call validateCartItems).
Build File Paths Changed
Imports through use-shopping-cart, use-shopping-cart/core and use-shopping-cart/utilities are unchanged. Importing use-shopping-cart/dist/... was already blocked by the package's exports map. Only tooling that bypasses it and points at a file breaks: an absolute path, a Jest moduleNameMapper, a bundler alias, or a CDN URL.
| v3 | v4 |
|---|---|
dist/react.es.js | dist/react.mjs |
dist/react.js | dist/react.cjs |
dist/core.es.js | dist/core.mjs |
dist/core.js | dist/core.cjs |
utilities/serverless.js | dist/utilities.mjs / dist/utilities.cjs |
dist/react.umd.js and dist/core.umd.js keep their names.
Errors Are CartErrors
Errors thrown by the cart, useCartActions forms, validateCartItems and redirectToCheckout are now CartErrors with a code (for example ITEM_NOT_IN_CART, NOT_IN_INVENTORY). Some messages changed (for example invalid count and quantity errors), so match on code rather than message. Validation errors previously had name: 'ValidationError'; they now have name: 'CartError'. useCartActions states have a new errorCode field. See error codes.
CartConfig Is Its Own Type
CartProvider props and the ShoppingCart constructor take only cartDetails, currency, language, shouldPersist, persistKey and storage. Other fields, like cartCount or shouldDisplayCart, were accepted before and silently ignored or copied into state; they're now type errors. shouldPersist is no longer part of the cart state (useShoppingCart().shouldPersist and initialState.shouldPersist are gone).
validateCartItems Matches More ID Fields
Inventory is now matched by id, price_id, sku_id and sku (first match in inventory wins), the same fields the cart uses for product ids. Carts with entries added by price_id or sku_id alone now validate instead of failing with "not in your inventory". Check your inventory if one product's price_id or sku_id can equal another product's id or sku: the earlier product now matches.
CartProvider Renders on the Server; loading Removed
CartProvider now renders its children during server rendering. The server and the first client render show the cart from your props (cartDetails, formatted with language, or en-US if you don't set it); the cart saved in storage and the browser's language apply right after hydration. Before, the server rendered the loading prop instead, which made hydration fail. Remove loading from <CartProvider>. cart.getInitialState() returns that server-side state, and initialState.language is now always en-US (it used to be the browser's language in the browser).
useOptimisticCart Reports Pending Entries in pendingIds
useOptimisticCart() no longer adds _optimistic: true to cart entries; its cartDetails hold plain CartEntrys. Read the new pendingIds set instead: pendingIds.has(item.id) replaces item._optimistic. The OptimisticCartEntry and OptimisticCartDetails types are removed; use CartEntry and CartDetails.
createNoopStorage Removed
Use shouldPersist={false} instead of storage={createNoopStorage()}; both store nothing.
Cart Entry Metadata Moved Under metadata
product_metadata and price_metadata from addItem are now stored as the entry's product_data.metadata and price_data.metadata, instead of being spread into product_data and price_data. This is what makes validateCartItems send product_metadata to Stripe Checkout; before, it was silently dropped. price_metadata stays in the cart, because Checkout's inline prices can't carry metadata.
// Before
entry.product_data.gift_wrap
// After
entry.product_data.metadata.gift_wrapredirectToCheckout Is a Standalone Function
Import it instead of reading it from the cart, and pass the Checkout Session URL. Session IDs, the stripe prop and changeStripeKey are gone: Stripe removed redirectToCheckout({ sessionId }) from Stripe.js, and a session URL needs no publishable key.
// Before
const { redirectToCheckout } = useShoppingCart()
await redirectToCheckout(sessionId)
// After: return session.url from your server
import { redirectToCheckout } from 'use-shopping-cart'
redirectToCheckout(sessionUrl)useShoppingCart(selector) Is Back
As in v3, useShoppingCart takes an optional selector, and the component re-renders only when the selected value changes:
const cartCount = useShoppingCart((cart) => cart.cartCount)loadCart Checks Its Cart Entries
loadCart now throws a CartError with code INVALID_CART, and leaves the cart unchanged, if cartDetails isn't an object or an entry is missing a string id, name or currency, a finite price, or a quantity that's an integer greater than 0. Before, such entries loaded with NaN totals, and loadCart(null, false) emptied the cart. value and the formatted fields are recomputed, so you can leave them out. If you load carts from your server, pass the cart entries themselves, not an object that wraps them:
// Before: loaded a broken entry named "cartDetails"
loadCart(savedCart, false) // savedCart is { cartDetails: { ... } }
// After
loadCart(savedCart.cartDetails, false)Apart from the breaking changes above, cart methods (addItem, incrementItem, removeItem, ...) work as before, and so does cart state (cartCount, cartDetails, ...).
What's New in v4.0
React 19 Support
Full compatibility with React 19, including support for:
useOptimistic, throughuseOptimisticCart, for optimistic changes while your backend syncsuseActionStatefor form-based cart actions- Concurrent rendering features
Improved Performance
- No Redux: the React entry is about 8 KB gzipped
- Better TypeScript support
What's Changed
1. Redux Removal (Internal Change)
Impact: None on your code
What happened:
- Removed Redux as an internal dependency
- Now uses React's native
useSyncExternalStorehook - Uses a custom
ShoppingCartclass with pub/sub pattern
Benefits:
- Smaller bundle size: no Redux, React-Redux or Redux Toolkit
- Better performance: Fewer re-renders
- Simpler mental model: No Redux concepts to understand
- React 19 compatible: Works with React's latest features
Migration: No action required. This is an internal refactor.
2. Client-Only Mode Removed
Impact: Projects using cartMode="client-only" must migrate
Status: Removed in v4.0
Required: Migrate to checkout-session mode
Migration Example
Before (Client-Only - v3.x):
import { CartProvider } from 'use-shopping-cart'
export const Root = () => (
<CartProvider
mode="payment"
cartMode="client-only"
stripe={STRIPE_KEY}
successUrl="https://yoursite.com/success"
cancelUrl="https://yoursite.com/cancel"
currency="USD"
>
<App />
</CartProvider>
)After (Checkout-Session - v4.0):
import { CartProvider } from 'use-shopping-cart'
export const Root = () => (
<CartProvider currency="USD">
<App />
</CartProvider>
)Additional Steps Required:
- Create a server endpoint to generate checkout sessions
- Move
successUrlandcancelUrlto server-side
See: Getting Started for detailed setup guide.
3. React Version Requirement
Before: React 16.8+
After: React 19+
Migration:
npm install react@19 react-dom@19Checkout Features
For checkout-session mode, modern Stripe features (phone collection, promotion codes, automatic tax, custom fields, shipping options, etc.) should be configured server-side when creating your checkout session:
// In your server endpoint
const session = await stripe.checkout.sessions.create({
mode: 'payment',
line_items,
success_url: `${origin}/success`,
cancel_url: origin,
// Configure Stripe features server-side
phone_number_collection: { enabled: true },
allow_promotion_codes: true,
automatic_tax: { enabled: true },
shipping_options: [
{
shipping_rate_data: {
display_name: 'Standard Shipping',
type: 'fixed_amount',
fixed_amount: { amount: 500, currency: 'usd' }
}
}
]
})See: Stripe Checkout Session API for all available options.
TypeScript Improvements
Better Type Exports
import type {
CartState,
CartConfig,
Product,
CartEntry,
CartDetails
} from 'use-shopping-cart/core'Improved Type Inference
const { cartDetails } = useShoppingCart()
// cartDetails is now properly typed
Object.values(cartDetails).forEach((item) => {
console.log(item.name) // ✓ TypeScript knows all properties
})Performance Improvements
Reduced Bundle Size
v4 drops Redux, React-Redux and Redux Toolkit. The use-shopping-cart entry is about 8 KB minified and gzipped, with React as its only dependency.
Fewer Re-renders
Pass a selector to useShoppingCart and a component re-renders only when the value it selects changes (see useShoppingCart).
API Stability
Unchanged APIs
These work as in v3:
✅ addItem(product, options?) (metadata now lives under metadata, see above)
✅ incrementItem(id, options?)
✅ decrementItem(id, options?)
✅ setItemQuantity(id, quantity)
✅ removeItem(id)
✅ clearCart()
✅ Cart state (cartCount, totalPrice, formattedTotalPrice, cartDetails, shouldDisplayCart, lastClicked)
Everything else listed under Breaking Changes needs updating, including redirectToCheckout, the stripe prop and client-only mode.
Step-by-Step Migration
Step 1: Update Dependencies
npm install use-shopping-cart@rc react@19 react-dom@19Step 2: Test Your Application
Update anything listed under Breaking Changes, then run your application and your tests.
Step 3: Configure Stripe Features (Server-Side)
If you want modern Stripe checkout features, configure them in your server endpoint:
// pages/api/create-checkout-session.js
const session = await stripe.checkout.sessions.create({
mode: 'payment',
line_items,
success_url: `${origin}/success`,
cancel_url: origin,
// Configure features server-side
phone_number_collection: { enabled: true },
allow_promotion_codes: true,
automatic_tax: { enabled: true }
})Step 4: Migrate from Client-Only (If Applicable)
If using cartMode="client-only", plan migration to checkout-session:
- Create server endpoint for session creation
- Update CartProvider configuration
- Test checkout flow
- Deploy
See: Getting Started for complete setup guide
Troubleshooting
React Version Errors
Error: "Invalid hook call" or "React version mismatch"
Solution: Ensure React 19 is installed:
npm install react@19 react-dom@19TypeScript Errors
Error: Type errors after upgrading
Solution: Update @types packages:
npm install -D @types/react@19 @types/react-dom@19Checkout Not Working
Issue: Checkout redirects not working
Check:
- Your server endpoint returns
session.url(notsession.id) - You pass that URL to
redirectToCheckout
Getting Help
Summary
Mostly Compatible ✅
- Cart methods and cart state work as before, apart from the breaking changes above
- Check the breaking changes:
redirectToCheckoutis now an import that takessession.url,CartConfigis narrower, and errors areCartErrors - Opt in to new features when ready
Major Improvements ✨
- Smaller bundle (no Redux)
- Better performance
- React 19 support
- Improved TypeScript
- Simpler architecture
Removed ❌
- Client-only mode (must migrate to checkout-session)
- All client-only mode props (
mode,cartMode,successUrl,cancelUrl,billingAddressCollection,allowedCountries) - Support for Node.js versions below 22
- The old
dist/*.es.js/dist/*.jsfile names (use the package entry points) redirectToCheckoutas a cart method, session-ID redirects, andRedirectToCheckoutInput(importredirectToCheckoutand passsession.url)- The
stripeprop andchangeStripeKey - The
RemoveItemStateandUpdateQuantityStatetypes (aliases; useItemStateandQuantityState) productId,itemIdandquantityonActionState(they're onAddItemState,ItemStateandQuantityState)shouldPersistandstripein the cart state, andCartStatefields asCartProviderprops
Checkout-session apps mostly need to update how they redirect to checkout. Client-only apps need a server endpoint that creates checkout sessions. Both are covered under Breaking Changes.
