decrementItem()
Decreases the quantity of an item in the cart by 1 (or by a custom amount). If the quantity reaches 0, the item is automatically removed.
Basic Usage
import { useShoppingCart } from 'use-shopping-cart'
function CartItem({ itemId }: { itemId: string }) {
const { decrementItem, cartDetails } = useShoppingCart()
const item = cartDetails[itemId]
return (
<div className="cart-item">
<span>{item.name}</span>
<span>Quantity: {item.quantity}</span>
<button onClick={() => decrementItem(itemId)}>-1</button>
</div>
)
}Decrement by Custom Amount
You can decrease the quantity by more than 1 (positive integers only):
// Decrease by 10
decrementItem(itemId, { count: 10 })Complete Cart Example
function Cart() {
const { decrementItem, cartDetails, cartCount } = useShoppingCart()
if (cartCount === 0) {
return <p>Your cart is empty</p>
}
return (
<div>
{Object.entries(cartDetails).map(([id, item]) => (
<div key={id} className="cart-item">
<h4>{item.name}</h4>
<p>Quantity: {item.quantity}</p>
<button onClick={() => decrementItem(id)}>-</button>
<button onClick={() => decrementItem(id, { count: 5 })}>-5</button>
</div>
))}
</div>
)
}Notes
- Automatically removes item from cart when quantity reaches 0
- Counts must be positive integers
Interactive Demo
Cart Display
Total Items: 0
Cart is empty. Add items to see them here!
Bananas
Yummy yellow fruit
$4.00
Add to Cart First:
Add items to your cart to try decrementing
Try decrementing items above! The cart state persists across all documentation pages.
