Skip to content

Context with a Reducer

The Course
•
20 min study

Yesterday's reducer gathered every update into one function. Today's context can deliver values anywhere. Together, they let any component read the board and dispatch actions to it, with no props passed through the middle.

The board through context React · 10 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import { useBoardDispatch } from "./BoardContext.jsx"; export default function AddCard() { const dispatch = useBoardDispatch(); const [title, setTitle] = useState(""); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; dispatch({ type: "card_added", id: Date.now(), title: title.trim(), minutes: 15 }); setTitle(""); } return ( <form className="toolbar" onSubmit={handleSubmit}> <input aria-label="New card" placeholder="New card" value={title} onChange={(e) => setTitle(e.target.value)} /> <button type="submit">Add</button> </form> ); } import AddCard from "./AddCard.jsx"; import Board from "./Board.jsx"; import { BoardProvider } from "./BoardContext.jsx"; export default function App() { return ( <BoardProvider> <main> <h1>Study Board</h1> <AddCard /> <Board /> </main> </BoardProvider> ); } import Column from "./Column.jsx"; import { useCards } from "./BoardContext.jsx"; import { columns } from "./data.js"; export default function Board() { const cards = useCards(); return ( <div className="board"> {columns.map((column, index) => ( <Column key={column.id} title={column.title} next={columns[index + 1]} cards={cards.filter((card) => card.column === column.id)} /> ))} </div> ); } import { createContext, useContext, useReducer } from "react"; import { boardReducer } from "./boardReducer.js"; import { starterCards } from "./data.js"; const CardsContext = createContext(null); const DispatchContext = createContext(null); export function BoardProvider({ children }) { const [cards, dispatch] = useReducer(boardReducer, starterCards); return ( <CardsContext value={cards}> <DispatchContext value={dispatch}>{children}</DispatchContext> </CardsContext> ); } export function useCards() { const cards = useContext(CardsContext); if (cards === null) throw new Error("useCards must be used inside <BoardProvider>."); return cards; } export function useBoardDispatch() { const dispatch = useContext(DispatchContext); if (dispatch === null) throw new Error("useBoardDispatch must be used inside <BoardProvider>."); return dispatch; } // Every change to the cards, in one place. A reducer takes the current state // and an action describing what happened, and returns the next state. export function boardReducer(cards, action) { switch (action.type) { case "card_added": return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }]; case "card_moved": return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card)); case "card_removed": return cards.filter((card) => card.id !== action.id); default: throw new Error(`Unknown action: ${action.type}`); } } import { useBoardDispatch } from "./BoardContext.jsx"; export default function CardItem({ card, next }) { const dispatch = useBoardDispatch(); return ( <li className="card"> <strong>{card.title}</strong> <div className="muted">{card.minutes} min</div> {next && ( <button onClick={() => dispatch({ type: "card_moved", id: card.id, column: next.id })} aria-label={`Move ${card.title} to ${next.title}`}>→</button> )}{" "} <button onClick={() => dispatch({ type: "card_removed", id: card.id })} aria-label={`Remove ${card.title}`}>×</button> </li> ); } import CardItem from "./CardItem.jsx"; export default function Column({ title, next, cards }) { return ( <section className="column"> <h2> {title} <span className="count">({cards.length})</span> </h2> <ul className="cards"> {cards.map((card) => ( <CardItem key={card.id} card={card} next={next} /> ))} </ul> </section> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Add, move and remove cards. Then open the files in this order: BoardContext.jsx, App.jsx, AddCard.jsx, CardItem.jsx.

The provider component

BoardContext.jsx holds everything about the board's state:

  • BoardProvider calls useReducer, then provides cards through one context and dispatch through another. Its children are whatever App puts inside it:

    JSX
    export function BoardProvider({ children }) {
      const [cards, dispatch] = useReducer(boardReducer, starterCards);
    
      return (
        <CardsContext value={cards}>
          <DispatchContext value={dispatch}>{children}</DispatchContext>
        </CardsContext>
      );
    }
  • useCards() and useBoardDispatch() are small custom hooks. Components call them instead of useContext directly, so they never need to import the context objects themselves. (Day 5 is all about custom hooks.)

    JSX
    export function useCards() {
      const cards = useContext(CardsContext);
      if (cards === null) throw new Error("useCards must be used inside <BoardProvider>.");
      return cards;
    }
    
    export function useBoardDispatch() {
      const dispatch = useContext(DispatchContext);
      if (dispatch === null) throw new Error("useBoardDispatch must be used inside <BoardProvider>.");
      return dispatch;
    }

App.jsx is now very short: it wraps the page in <BoardProvider>:

JSX
export default function App() {
  return (
    <BoardProvider>
      <main>
        <h1>Study Board</h1>
        <AddCard />
        <Board />
      </main>
    </BoardProvider>
  );
}

Components dispatch directly

AddCard and CardItem call useBoardDispatch() and dispatch actions themselves. Compare Column with yesterday's: it no longer passes onMove and onRemove down. Only next, which column a card moves to, is still a prop, because it's about layout, not board state:

JSX
export default function CardItem({ card, next }) {
  const dispatch = useBoardDispatch();

  return (
    <li className="card">
      <strong>{card.title}</strong>
      <div className="muted">{card.minutes} min</div>
      {next && (
        <button onClick={() => dispatch({ type: "card_moved", id: card.id, column: next.id })}
          aria-label={`Move ${card.title} to ${next.title}`}>→</button>
      )}{" "}
      <button onClick={() => dispatch({ type: "card_removed", id: card.id })} aria-label={`Remove ${card.title}`}>×</button>
    </li>
  );
}

Why two contexts?

dispatch never changes; React gives you the same function every render. The cards change when the reducer returns new data. With separate contexts, a component that only dispatches, like AddCard, isn't notified by card-context changes. In this lab it also receives the same children from App, so it skips those renders. A component can still re-render because its own state, its props, or its parent changed; splitting contexts doesn't prevent that. The next lesson measures the difference.

When is this worth it?

Context plus a reducer is the standard way to manage app-wide state in plain React. For a small screen, props are simpler and easier to follow. Reach for this pattern when many components at different depths read or change the same state.

Exercise

A count in the heading

Add a CardCount component that shows 4 cards next to the heading in App, using useCards(). It should update when cards are added or removed.

Your working space React · 10 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import { useBoardDispatch } from "./BoardContext.jsx"; export default function AddCard() { const dispatch = useBoardDispatch(); const [title, setTitle] = useState(""); function handleSubmit(event) { event.preventDefault(); if (title.trim() === "") return; dispatch({ type: "card_added", id: Date.now(), title: title.trim(), minutes: 15 }); setTitle(""); } return ( <form className="toolbar" onSubmit={handleSubmit}> <input aria-label="New card" placeholder="New card" value={title} onChange={(e) => setTitle(e.target.value)} /> <button type="submit">Add</button> </form> ); } import AddCard from "./AddCard.jsx"; import Board from "./Board.jsx"; import { BoardProvider } from "./BoardContext.jsx"; export default function App() { return ( <BoardProvider> <main> <h1>Study Board</h1> <AddCard /> <Board /> </main> </BoardProvider> ); } import Column from "./Column.jsx"; import { useCards } from "./BoardContext.jsx"; import { columns } from "./data.js"; export default function Board() { const cards = useCards(); return ( <div className="board"> {columns.map((column, index) => ( <Column key={column.id} title={column.title} next={columns[index + 1]} cards={cards.filter((card) => card.column === column.id)} /> ))} </div> ); } import { createContext, useContext, useReducer } from "react"; import { boardReducer } from "./boardReducer.js"; import { starterCards } from "./data.js"; const CardsContext = createContext(null); const DispatchContext = createContext(null); export function BoardProvider({ children }) { const [cards, dispatch] = useReducer(boardReducer, starterCards); return ( <CardsContext value={cards}> <DispatchContext value={dispatch}>{children}</DispatchContext> </CardsContext> ); } export function useCards() { const cards = useContext(CardsContext); if (cards === null) throw new Error("useCards must be used inside <BoardProvider>."); return cards; } export function useBoardDispatch() { const dispatch = useContext(DispatchContext); if (dispatch === null) throw new Error("useBoardDispatch must be used inside <BoardProvider>."); return dispatch; } // Every change to the cards, in one place. A reducer takes the current state // and an action describing what happened, and returns the next state. export function boardReducer(cards, action) { switch (action.type) { case "card_added": return [...cards, { id: action.id, title: action.title, column: "todo", minutes: action.minutes }]; case "card_moved": return cards.map((card) => (card.id === action.id ? { ...card, column: action.column } : card)); case "card_removed": return cards.filter((card) => card.id !== action.id); default: throw new Error(`Unknown action: ${action.type}`); } } import { useBoardDispatch } from "./BoardContext.jsx"; export default function CardItem({ card, next }) { const dispatch = useBoardDispatch(); return ( <li className="card"> <strong>{card.title}</strong> <div className="muted">{card.minutes} min</div> {next && ( <button onClick={() => dispatch({ type: "card_moved", id: card.id, column: next.id })} aria-label={`Move ${card.title} to ${next.title}`}>→</button> )}{" "} <button onClick={() => dispatch({ type: "card_removed", id: card.id })} aria-label={`Remove ${card.title}`}>×</button> </li> ); } import CardItem from "./CardItem.jsx"; export default function Column({ title, next, cards }) { return ( <section className="column"> <h2> {title} <span className="count">({cards.length})</span> </h2> <ul className="cards"> {cards.map((card) => ( <CardItem key={card.id} card={card} next={next} /> ))} </ul> </section> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

The count is derived from shared cards. Reading the context is enough; the count needs no separate state.

Hint 2: a first step

CardCount must render inside <BoardProvider>. App already places the <main> there, so put it next to the <h1>.

Show one solution
JSX
import { useCards } from "./BoardContext.jsx";

export default function CardCount() {
  const cards = useCards();
  return <span className="muted">{cards.length} cards</span>;
}

In App.jsx:

JSX
<h1>Study Board <CardCount /></h1>

Was this article helpful?

Your response is saved on this device.