React · Lesson 50 of 120
Reducer with Context
App-wide state.
Reducers and context work well together. The reducer manages the state. Context shares the state and dispatch, with every component that needs them.
- Reducer manages
- Context shares
- Any component
A shared cart
The cart reducer adds an item, or clears the cart. App creates the reducer, and provides the items and dispatch through context. Any component can now read the cart, or dispatch to it. The badge reads the items, and the buttons dispatch add actions. We add a helmet and lights. Run it.
App.jsxjsx
import { createContext, useContext, useReducer } from "react";
const CartContext = createContext(null);
function cartReducer(items, action) {
return action.type === "add" ? [...items, action.name] : [];
}
function AddButton({ name }) {
const { dispatch } = useContext(CartContext);
return <button id={name} onClick={() => dispatch({ type: "add", name })}>Add {name}</button>;
}
function CartBadge() {
const { items } = useContext(CartContext);
return <p className="box">Cart: {items.length} — {items.join(", ")}</p>;
}
export default function App() {
const [items, dispatch] = useReducer(cartReducer, []);
return <CartContext value={{ items, dispatch }}>
<CartBadge /><AddButton name="Helmet" /><AddButton name="Lights" />
</CartContext>;
}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": "#Helmet"}, {"click": "#Lights"}]Summary
Provide a reducer's state and dispatch through context, for simple app-wide state. Next, practice with a shopping cart.
Key takeaways- useReducer
- Context
- Anywhere
Next up: Practice: A Shopping Cart — reducer together