AI Hints
Home›React Tutorial›Reducers
React · Lesson 51 of 120

Practice: A Shopping Cart

Reducer together.

⏱ 2 min read▶ Video at 41:46🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Let's practise reducers with a real cart. Adding the same item twice should increase its quantity. And each line can be removed.

  • A real cart
  • Quantities
  • Remove lines

A cart reducer

The reducer handles two actions. Remove filters the item out. Add either increases the quantity, or adds a new line. The total is derived from the items. We add two helmets and some lights, then remove the helmets. Run it.

App.jsxjsx
import { useReducer } from "react";
function cart(items, { type, name, price }) {
  if (type === "remove") return items.filter(i => i.name !== name);
  const found = items.find(i => i.name === name);
  if (found) return items.map(i => (i === found ? { ...i, qty: i.qty + 1 } : i));
  return [...items, { name, price, qty: 1 }];
}
export default function App() {
  const [items, dispatch] = useReducer(cart, []);
  const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  const add = (name, price) => dispatch({ type: "add", name, price });
  return (<div>
    <button id="h" onClick={() => add("Helmet", 40)}>+ Helmet</button>
    <button id="l" onClick={() => add("Lights", 25)}>+ Lights</button>
    {items.map(i => <p key={i.name}>{i.qty} × {i.name}
      <button id={"x" + i.name} onClick={() => dispatch({ type: "remove", name: i.name })}>Remove</button></p>)}
    <p className="box">Total: £{total}</p>
  </div>);
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#h", "times": 2}, {"click": "#l"}, {"click": "#xHelmet"}]

Summary

A reducer keeps all the cart logic in one tested place. Next, a new section on custom hooks.

Key takeaways
  • add
  • remove
  • Derived total
Next up: Custom Hooks — reuse logic