useOptimisticCart()
New in v4.0.0 - Optimistic version of useShoppingCart() built on React 19's useOptimistic. It shows cart changes instantly while your backend confirms them.
Overview
useOptimisticCart() wraps useShoppingCart() for carts that sync with your backend. Pass an async onChange and every cart change shows in the UI immediately, is sent to onChange, and is applied to the real cart once onChange resolves. If it rejects, the change is rolled back.
Without onChange, its actions apply to the cart immediately, like useShoppingCart(). It still shows changes that other useOptimisticCart({ onChange }) calls on the same cart are waiting on.
Benefits
✅ Instant UI feedback - Changes show while your backend request is in flight
✅ Automatic rollback - If onChange rejects, the UI reverts and error is set
✅ In order - Changes are sent to onChange one at a time, in the order they were made
✅ Drop-in replacement - Returns the same values and actions as useShoppingCart() (it takes options, not a selector)
Requirements
- React 19.0.0 or higher
- use-shopping-cart v4.0.0 or higher
Basic Usage
The examples on this page use a syncCart function that sends each change to your backend:
async function syncCart(change) {
const res = await fetch('/api/cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(change)
})
if (!res.ok) throw new Error('Could not update cart')
}import { useOptimisticCart } from 'use-shopping-cart'
function ProductCard({ product }) {
const { addItem, isOptimistic } = useOptimisticCart({ onChange: syncCart })
return (
<button onClick={() => addItem(product)} disabled={isOptimistic}>
{isOptimistic ? 'Adding...' : 'Add to Cart'}
</button>
)
}Syncing with Your Backend
import { useOptimisticCart } from 'use-shopping-cart'
function Cart() {
const { cartDetails, incrementItem, isOptimistic, error } = useOptimisticCart(
{
onChange: async (change) => {
const res = await fetch('/api/cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(change)
})
if (!res.ok) throw new Error('Could not update cart')
}
}
)
// ...
}change describes what happened:
type | Fields | From |
|---|---|---|
'add' | id, product, count, metadata (price_metadata, product_metadata) | addItem |
'adjust' | id, by (negative for decrements) | incrementItem, decrementItem |
'set' | id, quantity | setItemQuantity |
'remove' | id | removeItem |
'clear' | clearCart |
id is the cart entry's key in cartDetails. The changes that follow use the same id, so your backend can match them to the add, even when the cart generated the id for a product without one.
How it behaves:
- Every component:
<CartProvider>holds oneuseOptimisticstate per cart, so a pending change shows in every component that callsuseOptimisticCart. A total in one component updates when a cart entry in another changes.useShoppingCartshows only confirmed changes. - Order: changes wait for the previous
onChangeto settle, so three quick clicks send three requests, one after another. Changes made withoutonChangedon't wait: they apply to the cart straight away. - Success: the change is applied to the real cart (and saved to
storage). - Failure: the change is dropped and
errorholds whatonChangethrew, in the component that made the change. Later queued changes still run, but each is checked against the real cart first: one that depended on the failed change (incrementing a cart entry whose add failed) is dropped with anITEM_NOT_IN_CARTerror and never reachesonChange. - Rollback timing: React batches pending transitions together, so if one change fails while others are still pending, its rollback shows once they settle.
- Invalid input (bad count, product without a price) throws immediately and never reaches
onChange.
What the server does with the change is up to you. Don't call loadCart with the server's cart inside onChange: the change is applied to the cart after onChange resolves, so a server cart that already includes it gets the change twice. Load the server's cart outside onChange, for example when the page loads.
API
Options
| Option | Type | Description |
|---|---|---|
onChange | (change: CartChange) => Promise<unknown> | unknown | Called for each change before it reaches the cart |
useOptimisticCart() returns the same properties and methods as useShoppingCart(), plus:
Additional Properties
isOptimistic
- Type:
boolean - Description:
truewhen the cart is showing optimistic changes that haven't been confirmed yet
const { isOptimistic } = useOptimisticCart({ onChange: syncCart })
{
isOptimistic && <span>Syncing changes...</span>
}error
- Type:
unknown - Description: what
onChangethrew for the last change this component made;nullafter one succeeds
pendingIds
- Type:
ReadonlySet<string> - Description: ids of the cart entries an optimistic change added or changed that the backend hasn't confirmed yet; empty when nothing is in flight
const { cartDetails, pendingIds } = useOptimisticCart({ onChange: syncCart })
Object.values(cartDetails).map((item) => (
<div key={item.id}>
{item.name} - Qty: {item.quantity}
{pendingIds.has(item.id) && <span> (updating...)</span>}
</div>
))Examples
Cart with Loading States
function ShoppingCart() {
const {
cartDetails,
cartCount,
formattedTotalPrice,
clearCart,
isOptimistic
} = useOptimisticCart({ onChange: syncCart })
return (
<div className="cart">
<h2>Your Cart ({cartCount} items)</h2>
{isOptimistic && (
<div className="syncing-indicator">🔄 Syncing changes...</div>
)}
{Object.values(cartDetails).map((item) => (
<CartItem key={item.id} item={item} />
))}
<div className="cart-total">
Total:{' '}
<span className={isOptimistic ? 'updating' : ''}>
{formattedTotalPrice}
</span>
</div>
<button onClick={clearCart} disabled={isOptimistic}>
Clear Cart
</button>
</div>
)
}Cart Entry with Quantity Controls
function CartItem({ item }) {
const { incrementItem, decrementItem, removeItem, isOptimistic, pendingIds } =
useOptimisticCart({ onChange: syncCart })
return (
<div className="cart-item">
<h4>{item.name}</h4>
<div className="quantity-controls">
<button
onClick={() => decrementItem(item.id)}
disabled={isOptimistic || item.quantity === 1}
>
-
</button>
<span className={pendingIds.has(item.id) ? 'updating' : ''}>
{item.quantity}
</span>
<button onClick={() => incrementItem(item.id)} disabled={isOptimistic}>
+
</button>
</div>
<button onClick={() => removeItem(item.id)} disabled={isOptimistic}>
Remove
</button>
</div>
)
}Advanced: Per-Item Loading
function ProductCard({ product }) {
const { addItem, cartDetails, pendingIds } = useOptimisticCart({
onChange: syncCart
})
const itemInCart = cartDetails[product.id]
const isThisItemOptimistic = pendingIds.has(product.id)
return (
<div className="product">
<h3>{product.name}</h3>
<p>${product.price / 100}</p>
{itemInCart && (
<div className="in-cart-badge">
In cart: {itemInCart.quantity}
{isThisItemOptimistic && ' (updating...)'}
</div>
)}
<button onClick={() => addItem(product)} disabled={isThisItemOptimistic}>
{isThisItemOptimistic ? 'Adding...' : 'Add to Cart'}
</button>
</div>
)
}Migration from useShoppingCart()
Replace useShoppingCart with useOptimisticCart and pass the function that syncs with your backend:
- import { useShoppingCart } from 'use-shopping-cart'
+ import { useOptimisticCart } from 'use-shopping-cart'
function MyComponent() {
- const { addItem, cartCount } = useShoppingCart()
+ const { addItem, cartCount, isOptimistic } = useOptimisticCart({
+ onChange: syncCart
+ })
return (
<button onClick={() => addItem(product)}>
- Add to Cart
+ {isOptimistic ? 'Adding...' : 'Add to Cart'}
</button>
)
}When to Use
Use useOptimisticCart() when:
- Your cart syncs with a backend and you want changes to show before the request finishes
Stick with useShoppingCart() when:
- The cart lives only in the browser (it's already instant)
- You sync with a backend some other way, for example with
subscribe
TypeScript
import { useOptimisticCart, type CartChange, type Product } from 'use-shopping-cart'
async function syncCart(change: CartChange): Promise<void> {
await fetch('/api/cart', { method: 'POST', body: JSON.stringify(change) })
}
function ProductCard({ product }: { product: Product }) {
const { addItem, isOptimistic } = useOptimisticCart({ onChange: syncCart })
return (
<button onClick={() => addItem(product)} disabled={isOptimistic}>
{isOptimistic ? 'Adding...' : 'Add to Cart'}
</button>
)
}Interactive Demo
Cart Display
Total Items: 0
Cart is empty. Add items to see them here!
Bananas
Yummy yellow fruit
$4.00
Try Optimistic Updates:
💡 What's happening?
- The quantity under the product updates instantly, marked "confirming..."
- The cart on the left uses useShoppingCart, so it updates once the simulated server confirms
- Try the error button - UI automatically rolls back on failure
- Uses
useOptimisticCart({ onChange })with a simulated server
Note: 2.5 second delay added to this demo to showcase the confirmation state
Try adding products and watch the instant UI feedback! The demo's onChange simulates a server that takes a couple of seconds. The cart entry shows immediately with a "confirming" state, and the cart on the left updates once the simulated server confirms. "Add with Error" shows the rollback.
See Also
- useShoppingCart() - Standard cart hook without optimistic changes
- React 19 useOptimistic - React's official documentation
