Skip to content

Context Pitfalls

The Course
•
20 min study

This version of the board puts cards and dispatch in one context, as one object: value={{ cards, dispatch }}. It works, but it has two problems:

JSX
// One context holding both the cards and dispatch.
const BoardContext = createContext(null);

export function BoardProvider({ children }) {
  const [cards, dispatch] = useReducer(boardReducer, starterCards);
  return <BoardContext value={{ cards, dispatch }}>{children}</BoardContext>;
}

export function useBoard() {
  return useContext(BoardContext);
}
One context, one object React · 8 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import Board from "./Board.jsx"; import Header from "./Header.jsx"; import { BoardProvider } from "./BoardContext.jsx"; export default function App() { return ( <BoardProvider> <main> <Header /> <Board /> </main> </BoardProvider> ); } import { useBoard } from "./BoardContext.jsx"; import { columns } from "./data.js"; export default function Board() { const { cards, dispatch } = useBoard(); return ( <div className="board"> {columns.map((column) => ( <section key={column.id} className="column"> <h2>{column.title} <span className="count">({cards.filter((c) => c.column === column.id).length})</span></h2> <ul className="cards"> {cards.filter((c) => c.column === column.id).map((card) => ( <li key={card.id} className="card"> <strong>{card.title}</strong>{" "} <button onClick={() => dispatch({ type: "card_removed", id: card.id })} aria-label={`Remove ${card.title}`}>×</button> </li> ))} </ul> </section> ))} </div> ); } import { createContext, useContext, useReducer } from "react"; import { boardReducer } from "./boardReducer.js"; import { starterCards } from "./data.js"; // One context holding both the cards and dispatch. const BoardContext = createContext(null); export function BoardProvider({ children }) { const [cards, dispatch] = useReducer(boardReducer, starterCards); return <BoardContext value={{ cards, dispatch }}>{children}</BoardContext>; } export function useBoard() { return useContext(BoardContext); } // 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}`); } } 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 }, ]; import { useBoard } from "./BoardContext.jsx"; // Only dispatches; never reads the cards. export default function Header() { const { dispatch } = useBoard(); console.log("Header rendered"); return ( <div className="toolbar"> <h1>Study Board</h1> <button onClick={() => dispatch({ type: "card_added", id: Date.now(), title: "Quick card", minutes: 5 })}> Quick add </button> </div> ); } 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.

Pitfall 1: everything re-renders

Header only dispatches; it never reads the cards. It logs Header rendered each time it renders. Remove two cards and watch the console:

JSX
// Only dispatches; never reads the cards.
export default function Header() {
  const { dispatch } = useBoard();
  console.log("Header rendered");

  return (
    <div className="toolbar">
      <h1>Study Board</h1>
      <button onClick={() => dispatch({ type: "card_added", id: Date.now(), title: "Quick card", minutes: 5 })}>
        Quick add
      </button>
    </div>
  );
}
What you'll see

Header rendered appears again after every removal. Removing a card changes cards, and cards is part of the context value. When a context's value changes, every component that reads that context re-renders, whether or not it uses the part that changed. Header only wants dispatch, but it reads a value that contains cards, so it re-renders whenever cards does.

A second, separate problem hides in value={{ cards, dispatch }}: the braces build a new object on every render of BoardProvider. Here the provider only renders when cards changes, so it makes no extra difference. But if the provider's parent re-rendered for some unrelated reason, the new object would count as a changed value too, and every reader would re-render even with the same cards. Wrapping the object in useMemo fixes that second problem only: the value still changes with cards, so Header still re-renders on every removal. To stop that, Header must read a context that doesn't contain cards at all.

Fix it the way the last lesson did: two contexts, one for cards and one for dispatch. dispatch never changes, so a component that reads only the dispatch context never re-renders because of it. Replace BoardContext.jsx with:

JSX
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() {
  return useContext(CardsContext);
}

export function useBoardDispatch() {
  return useContext(DispatchContext);
}

Then make Header use useBoardDispatch(), and Board use both hooks. Run, remove two cards, and Header rendered appears only once, at the start.

For most screens, a few extra renders don't matter. Day 6 covers how to tell when they do. Splitting state from dispatch costs nothing, though, so do it from the start.

Pitfall 2: a missing provider fails silently, or strangely

In App.jsx, move <Header /> above <BoardProvider>, outside it. Run.

What you'll see

With the original one-object version, useBoard() returns the default, null, and the app crashes with Cannot destructure property 'dispatch' … as it is null. With the two-context version, useBoardDispatch() returns null silently, and the crash only comes when you press Quick add: dispatch is not a function. Either way, the message doesn't say what's actually wrong.

Make the custom hooks check, and say what's wrong:

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

Now the console names the mistake as soon as Header renders. This is why the custom hooks exist: one place to check, with a message that says how to fix it. Move <Header /> back inside.

Pitfall 3: context for everything

Context makes data flow harder to follow: a component can now depend on something no prop mentions. Before reaching for it, try:

  • Passing props. Two or three levels is fine, and it's explicit.
  • Composition, the next lesson: passing components as children so the middle layers don't need the data at all.
Exercise

Check the cards hook too

Give useCards() the same check, with the message useCards must be used inside <BoardProvider>., and confirm it fires when Board is rendered outside the provider.

Your working space React · 8 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import Board from "./Board.jsx"; import Header from "./Header.jsx"; import { BoardProvider } from "./BoardContext.jsx"; export default function App() { return ( <BoardProvider> <main> <Header /> <Board /> </main> </BoardProvider> ); } import { useBoard } from "./BoardContext.jsx"; import { columns } from "./data.js"; export default function Board() { const { cards, dispatch } = useBoard(); return ( <div className="board"> {columns.map((column) => ( <section key={column.id} className="column"> <h2>{column.title} <span className="count">({cards.filter((c) => c.column === column.id).length})</span></h2> <ul className="cards"> {cards.filter((c) => c.column === column.id).map((card) => ( <li key={card.id} className="card"> <strong>{card.title}</strong>{" "} <button onClick={() => dispatch({ type: "card_removed", id: card.id })} aria-label={`Remove ${card.title}`}>×</button> </li> ))} </ul> </section> ))} </div> ); } import { createContext, useContext, useReducer } from "react"; import { boardReducer } from "./boardReducer.js"; import { starterCards } from "./data.js"; // One context holding both the cards and dispatch. const BoardContext = createContext(null); export function BoardProvider({ children }) { const [cards, dispatch] = useReducer(boardReducer, starterCards); return <BoardContext value={{ cards, dispatch }}>{children}</BoardContext>; } export function useBoard() { return useContext(BoardContext); } // 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}`); } } 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 }, ]; import { useBoard } from "./BoardContext.jsx"; // Only dispatches; never reads the cards. export default function Header() { const { dispatch } = useBoard(); console.log("Header rendered"); return ( <div className="toolbar"> <h1>Study Board</h1> <button onClick={() => dispatch({ type: "card_added", id: Date.now(), title: "Quick card", minutes: 5 })}> Quick add </button> </div> ); } 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

A missing provider is a setup mistake. Detect it at the hook boundary so the error names the missing setup.

Hint 2: a first step

The same shape as useBoardDispatch: read the context, throw if it's null, return it.

Show one solution
JavaScript
export function useCards() {
  const cards = useContext(CardsContext);
  if (cards === null) throw new Error("useCards must be used inside <BoardProvider>.");
  return cards;
}

The default of null matters. Had the context been created with createContext([]), a missing provider would give an empty board with no error at all.

Was this article helpful?

Your response is saved on this device.