Hooks
useShoppingCart()
The main hook for accessing shopping cart state and methods. Returns all cart properties and action methods.
Signature
function useShoppingCart(): UseShoppingCartReturn
function useShoppingCart<T>(
selector: (cart: UseShoppingCartReturn) => T,
isEqual?: (previous: T, next: T) => boolean
): TUsage
import { useShoppingCart } from 'use-shopping-cart'
function MyComponent() {
const {
// Cart state
cartCount,
totalPrice,
formattedTotalPrice,
cartDetails,
// Cart actions
addItem,
removeItem,
incrementItem,
decrementItem,
clearCart
} = useShoppingCart()
// Use cart state and methods
}Selecting Part of the Cart
Pass a selector to read one value. The component re-renders only when that value changes, so a cart badge doesn't re-render when the drawer opens, and a button that only needs addItem never re-renders:
function CartBadge() {
const cartCount = useShoppingCart((cart) => cart.cartCount)
return <span>{cartCount}</span>
}
function AddToCart({ product }) {
const addItem = useShoppingCart((cart) => cart.addItem)
return <button onClick={() => addItem(product)}>Add</button>
}A selector that builds a new object ((cart) => ({ a: cart.a })) re-renders on every change. Pass isEqual to keep the previous result when nothing you care about changed:
const totals = useShoppingCart(
(cart) => ({ count: cart.cartCount, total: cart.formattedTotalPrice }),
(previous, next) =>
previous.count === next.count && previous.total === next.total
)Return Value
The hook returns an object with all cart state and methods:
Cart State Properties
| Property | Type | Description |
|---|---|---|
cartCount | number | Total quantity across all cart entries |
totalPrice | number | Total price in smallest currency unit |
formattedTotalPrice | string | Formatted total price with currency symbol |
cartDetails | object | Object containing all cart entries with details |
shouldDisplayCart | boolean | UI helper for displaying cart |
lastClicked | string | ID of last clicked product |
currency | string | Currency used for formatting |
language | string | Language used for formatting |
Cart Manipulation Methods
| Method | Description |
|---|---|
addItem(product, options?) | Add product to cart |
incrementItem(id, options?) | Increase quantity (default 1) |
decrementItem(id, options?) | Decrease quantity (default 1) |
setItemQuantity(id, quantity) | Set specific quantity |
removeItem(id) | Remove item from cart |
clearCart() | Remove all items |
loadCart(cartDetails, shouldMerge?) | Load cart from external source |
changeCurrency(currency) | Reformat prices in a currency |
changeLanguage(language) | Reformat prices for a language |
UI Helper Methods
| Method | Description |
|---|---|
handleCartClick() | Toggle cart display |
handleCartHover() | Handle cart hover |
handleCloseCart() | Close cart display |
storeLastClicked(productId) | Store last clicked product |
Complete Examples
Basic Cart Operations
import { useShoppingCart } from 'use-shopping-cart'
function ProductCard({ product }) {
const { addItem, cartDetails } = useShoppingCart()
const itemInCart = cartDetails[product.id]
return (
<div className="product">
<h3>{product.name}</h3>
<p>${product.price / 100}</p>
{itemInCart ? (
<p>In cart: {itemInCart.quantity}</p>
) : (
<button onClick={() => addItem(product)}>Add to Cart</button>
)}
</div>
)
}Cart Display Component
import { redirectToCheckout, useShoppingCart } from 'use-shopping-cart'
function CartSummary() {
const {
cartCount,
formattedTotalPrice,
cartDetails,
incrementItem,
decrementItem,
removeItem
} = useShoppingCart()
const handleCheckout = async () => {
const response = await fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cartDetails })
})
const { sessionUrl } = await response.json()
redirectToCheckout(sessionUrl)
}
if (cartCount === 0) {
return <p>Your cart is empty</p>
}
return (
<div className="cart">
<h2>Cart ({cartCount} items)</h2>
{Object.entries(cartDetails).map(([id, item]) => (
<div key={id} className="cart-item">
<h4>{item.name}</h4>
<p>{item.formattedPrice}</p>
<div className="quantity-controls">
<button onClick={() => decrementItem(id)}>-</button>
<span>{item.quantity}</span>
<button onClick={() => incrementItem(id)}>+</button>
<button onClick={() => removeItem(id)}>Remove</button>
</div>
</div>
))}
<div className="cart-total">
<h3>Total: {formattedTotalPrice}</h3>
<button onClick={handleCheckout}>Checkout</button>
</div>
</div>
)
}TypeScript Support
import { useShoppingCart, type Product } from 'use-shopping-cart'
const banana: Product = {
id: 'banana_001',
name: 'Bananas',
price: 400,
currency: 'USD'
}
function AddBanana() {
const addItem = useShoppingCart((cart) => cart.addItem)
return <button onClick={() => addItem(banana)}>Add bananas</button>
}Notes
- Must be used within a
<CartProvider>component - Methods keep the same identity for the life of the cart, so they're safe in dependency arrays
- Without a selector, the component re-renders on every cart change, including
shouldDisplayCartandlastClicked
See Also
- useOptimisticCart() - Optimistic UI updates
- useCartActions() - Form action integration
- CartProvider - Provider component
- Properties - All available properties
- Actions - All available methods
