ImportantThis 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.
TipThe getDetails() method automatically aggregates items with the same key. Use this for your "Cart Summary" view to show combined quantities and subtotals.
NoteAll 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.
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.
| Name | Type | Description |
|---|---|---|
| options | UseShoppingCartOptions<T> | Required. Configuration to interpret the item type T. |
| getItemKey | (item: T) => string | number | Required. Returns the unique identifier for an item. |
| getItemPrice | (item: T) => number | Required. Returns the unit price of the item. |
| getItemQuantity | (item: T) => number | Required. Returns current quantity. |
| getItemTax | (item: T) => number | Optional. Returns tax per unit. Default: 0. |
| getItemDiscount | (item: T) => number | Optional. Returns discount per unit. Default: 0. |
| Name | Type | Description |
|---|---|---|
| items | T[] | The raw array of items in the cart. |
| addItem | (item: T) => void | Appends a new item to the cart. |
| removeItem | (key: number | string) => void | Removes an item by its key. |
| updateItem | (key: number | string, patch: Partial<T>) => void | Updates specific properties of an item. |
| getTotal | () => number | Calculates total: Subtotal + Tax − Discount. |
| getDetails | () => ShoppingCartItemDetail[] | Returns a derived list of aggregated items with math details. |
| clear | () => void | Removes all items from the cart. |