useShoppingCart

A generic, domain-agnostic hook for managing complex shopping cart logic and calculations.

Important

This hook is stateless across page reloads. If you want the cart to persist after a browser refresh, you should wrap its initialization logic with localStorage or use a persistence provider.

Tip

The getDetails() method automatically aggregates items with the same key. Use this for your "Cart Summary" view to show combined quantities and subtotals.

Note

All calculation logic (taxes, discounts, totals) is derived from the extractor functions you provide. Ensure these functions handle edge cases like null or undefined prices gracefully.

Installation

bash

Description

This hook provides a comprehensive API for managing items in a cart. By using "extractor functions" for price, quantity, taxes, and IDs, it can work with any data structure without imposing a specific schema on the developer.

Parameters

NameTypeDescription
optionsUseShoppingCartOptions<T>Required. Configuration to interpret the item type T.
getItemKey(item: T) => string | numberRequired. Returns the unique identifier for an item.
getItemPrice(item: T) => numberRequired. Returns the unit price of the item.
getItemQuantity(item: T) => numberRequired. Returns current quantity.
getItemTax(item: T) => numberOptional. Returns tax per unit. Default: 0.
getItemDiscount(item: T) => numberOptional. Returns discount per unit. Default: 0.

Return values

NameTypeDescription
itemsT[]The raw array of items in the cart.
addItem(item: T) => voidAppends a new item to the cart.
removeItem(key: number | string) => voidRemoves an item by its key.
updateItem(key: number | string, patch: Partial<T>) => voidUpdates specific properties of an item.
getTotal() => numberCalculates total: Subtotal + Tax − Discount.
getDetails() => ShoppingCartItemDetail[]Returns a derived list of aggregated items with math details.
clear() => voidRemoves all items from the cart.

Demo

Shopping Cart

Items in cart: 0Total Quantity: 0Total Amount: $0
Details

Source code

tsx