Real World Example

Real World: Cart shared across an e-commerce app

The cart is needed in the header badge, product pages, the cart page and checkout. Redux keeps it in one store; each component selects only what it needs.

// header badge
function CartIcon() {
  const count = useSelector((s) => s.cart.items.reduce((n, i) => n + i.qty, 0));
  return <Link to="/cart">🛒 {count}</Link>;
}

// product page
function AddToCart({ product }) {
  const dispatch = useDispatch();
  return <button onClick={() => dispatch(addItem(product))}>Add to cart</button>;
}

// checkout total
const total = useSelector((s) => s.cart.items.reduce((sum, i) => sum + i.price * i.qty, 0));