use-shopping-cart logouse-shopping-cart
Concepts

Architecture

Understanding how use-shopping-cart works internally in v4.0.

Overview

Version 4.0 represents a complete architectural overhaul. The library moved from Redux to React's native state management, resulting in a simpler, lighter, and more performant solution.

Redux Removal

Before (v3.x)

v3.x used Redux for state management:

CartProvider → Redux Store → Redux Reducer → Cart State
                  ↓
            React Context
                  ↓
           useShoppingCart Hook

Dependencies:

  • redux
  • react-redux
  • @reduxjs/toolkit

After (v4.0)

v4.0 uses React's native useSyncExternalStore:

CartProvider → ShoppingCart Class → Pub/Sub Pattern → Cart State
                      ↓
              useSyncExternalStore
                      ↓
              useShoppingCart Hook

Dependencies:

  • None! (Just React 19+)

ShoppingCart Class

The core of v4.0 is the ShoppingCart class, which manages all cart state and operations.

Key Features

  1. Immutable State: All state updates create new objects
  2. Pub/Sub Pattern: Subscribers are notified of changes
  3. Persistence: Automatic localStorage sync
  4. Type-Safe: Full TypeScript support

Basic Structure

const cart = new ShoppingCart({ currency: 'USD' })

cart.subscribe((state) => console.log(state.cartCount))
cart.addItem(product)
cart.getState().cartDetails

See ShoppingCart Class for the full API.

React Integration

useSyncExternalStore

React 19's useSyncExternalStore connects components to the ShoppingCart:

function useShoppingCart(selector) {
  const cart = useContext(CartContext) // ShoppingCart instance

  return useSyncExternalStore(
    cart.subscribe,
    () => select(cart.getState(), selector),
    () => select(serverState, selector) // used while hydrating
  )
}

The real hook also binds the cart's methods once and caches each selection per state, so the snapshot only changes when the state does.

Benefits

  1. Automatic Re-renders: Components re-render when cart changes
  2. Selective Updates: With a selector, a component re-renders only when the value it selects changes
  3. No Provider Nesting: Single CartProvider at the root
  4. Concurrent Safe: Works with React 19 concurrent features

State Management Flow

Adding an Item

User clicks "Add to Cart"
         ↓
   addItem(product)
         ↓
  ShoppingCart.addItem()
         ↓
   Update internal state
         ↓
   Persist to localStorage
         ↓
   Notify all subscribers
         ↓
  Components re-render

State Immutability

All state updates create new objects:

// Wrong (mutates state)
this.state.cartDetails[id] = newItem

// Correct (creates new state)
this.state = {
  ...this.state,
  cartDetails: {
    ...this.state.cartDetails,
    [id]: newItem
  }
}

Persistence Layer

Storage Interface

interface StorageAdapter {
  getItem(key: string): Promise<string | null> | string | null
  setItem(key: string, value: string): Promise<void> | void
  removeItem(key: string): Promise<void> | void
}

Built-in Adapters

  1. createLocalStorage(): browser localStorage (default)
  2. createSessionStorage(): browser sessionStorage, cleared when the tab closes
  3. createMemoryStorage(): in memory, for tests

To store nothing, pass shouldPersist={false}.

On the server, the cart doesn't touch storage at all.

Custom Storage

const customStorage = {
  getItem: (key) => {
    // Get from your storage
    return sessionStorage.getItem(key)
  },
  setItem: (key, value) => {
    // Save to your storage
    sessionStorage.setItem(key, value)
  },
  removeItem: (key) => {
    // Remove from your storage
    sessionStorage.removeItem(key)
  }
}

<CartProvider storage={customStorage} />

Performance Optimizations

1. Memoized Methods

Cart methods are bound once per cart, so addItem and the others keep the same identity across renders and components. A component that selects only an action never re-renders:

const addItem = useShoppingCart((cart) => cart.addItem)

2. Selective Subscriptions

Pass a selector and a component re-renders only when the selected value changes. Without one, it re-renders on every cart change.

const cartCount = useShoppingCart((cart) => cart.cartCount)
const totalPrice = useShoppingCart((cart) => cart.totalPrice)

3. Precomputed Totals

cartCount, totalPrice and formattedTotalPrice are computed once per change and stored on the state, so reading them is free.

Bundle Size Comparison

Entry pointSize (minified + gzipped)
use-shopping-cart~8 KB
use-shopping-cart/core~5 KB
use-shopping-cart/utilities~1.5 KB

v4 has no runtime dependencies besides React. v3 also shipped Redux, React-Redux and Redux Toolkit.

Migration Impact

Code Changes

Cart methods (addItem, incrementItem, removeItem, ...) work as before, and so does cart state (cartCount, cartDetails, ...) apart from shouldPersist (now config only) and stripe (removed). A few APIs changed; see the migration guide.

What Changed Internally

  • ❌ Redux store
  • ❌ Redux actions
  • ❌ Redux reducers
  • ✅ ShoppingCart class
  • ✅ useSyncExternalStore
  • ✅ Pub/sub pattern

TypeScript Support

Type Inference

const { cartDetails } = useShoppingCart()

// TypeScript knows the exact shape
Object.values(cartDetails).forEach((item) => {
  console.log(item.name) // ✓ string
  console.log(item.quantity) // ✓ number
  console.log(item.price) // ✓ number
})

Exported Types

import type {
  CartState,
  CartConfig,
  Product,
  CartEntry,
  CartDetails,
  UseShoppingCartReturn
} from 'use-shopping-cart'

Debugging

Dev Tools

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

function App() {
  return (
    <CartProvider>
      <DebugCart />
      <YourApp />
    </CartProvider>
  )
}

Shows:

  • Current cart state
  • Cart actions
  • State changes in real-time

Logging

Enable logging in development:

const cart = new ShoppingCart(config)

cart.subscribe((state) => {
  console.log('Cart updated:', state)
})

Benefits of New Architecture

1. Simpler Mental Model

No need to understand Redux concepts:

  • No actions
  • No reducers
  • No dispatch

Just: "Call a method, state updates, components re-render"

2. Better Performance

  • Fewer dependencies
  • Smaller bundle
  • Faster initialization
  • More efficient updates

3. React 19 Native

  • Uses React's built-in features
  • Works with concurrent rendering
  • Server-renders and hydrates without mismatches
  • Future-proof

4. Easier Testing

// No Redux setup needed
const cart = new ShoppingCart(config)

cart.addItem(product)
expect(cart.getState().cartCount).toBe(1)

cart.removeItem(product.id)
expect(cart.getState().cartCount).toBe(0)

See Also

On this page

Shopping Cart

Your cart is empty

Try the interactive demos on the docs pages!