Sub topic 14
Sharing state with context
This chapter replaces the callbacks that you pass down through props with React context. It assumes you finished the earlier chapters. You should have a todosReducer, an App component that owns the to-do list, and presentational components such as TodoItem that receive todo, onToggle, and onDelete as props. You should also be comfortable with useReducer, dispatch, and the children prop.
The problem: prop drilling
In the current app, App owns the state. TodoItem needs onToggle and onDelete, and App doesn't render TodoItem directly. The data and callbacks travel through every component in between:
App → TodoList → TodoItem
TodoList doesn't use onToggle or onDelete. It only forwards them. This is called prop drilling. With two levels it is harmless. If you add a TodoGroup, a Toolbar, or a nested sub-task list, every layer has to accept and forward the same props. Renaming one prop then means editing many files.
Context lets a component read a value from an ancestor without receiving it through props at each level.
The three parts of context
Context has three parts:
createContext(defaultValue)creates a context object.<Context.Provider value={...}>makes a value available to everything rendered inside it.useContext(Context)reads the value from the nearest matching provider above the calling component.
The default value is used only when a component has no matching provider above it. Most apps don't have a sensible default for shared state. A common pattern is to use null as the default and fail loudly when it is read. You will do this below.
Combining context with the reducer
You already have a reducer, so you can expose two things to the tree: the current todos array and the dispatch function. Put both, and the provider that owns them, in one file.
// src/TodosContext.jsx
import { createContext, useContext, useReducer } from "react";
const TodosContext = createContext(null);
const TodosDispatchContext = createContext(null);
function todosReducer(todos, action) {
switch (action.type) {
case "added":
return [...todos, { id: action.id, title: action.title, done: false }];
case "toggled":
return todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
case "deleted":
return todos.filter((t) => t.id !== action.id);
default:
throw new Error("Unknown action: " + action.type);
}
}
export function TodosProvider({ children }) {
const [todos, dispatch] = useReducer(todosReducer, []);
return (
<TodosContext.Provider value={todos}>
<TodosDispatchContext.Provider value={dispatch}>
{children}
</TodosDispatchContext.Provider>
</TodosContext.Provider>
);
}
export function useTodos() {
const todos = useContext(TodosContext);
if (todos === null) {
throw new Error("useTodos must be used inside a TodosProvider");
}
return todos;
}
export function useTodosDispatch() {
const dispatch = useContext(TodosDispatchContext);
if (dispatch === null) {
throw new Error("useTodosDispatch must be used inside a TodosProvider");
}
return dispatch;
}Three design choices in this file are worth explaining.
- Two contexts, not one.
dispatchkeeps the same identity for the life of the component. Thetodosarray gets a new identity on every change. A component that only dispatches, such as the add form, doesn't need to re-render when the list changes. With a single{ todos, dispatch }context, it would. - Custom hooks instead of exporting the contexts. Components call
useTodos()and never seeuseContextor the context objects. You can change how the state is stored later without touching consumers. - The
nullcheck. If you forget the provider,useContextquietly returns the default. Without the check, you would seeCannot read properties of nullsomewhere far from the cause. With the check, the error names the missing provider.
Wiring the provider
Wrap the part of the tree that needs the state. For a small app, that is the whole app.
// src/main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { TodosProvider } from "./TodosContext";
createRoot(document.getElementById("root")).render(
<StrictMode>
<TodosProvider>
<App />
</TodosProvider>
</StrictMode>
);Now App no longer owns the list or the callbacks. It composes the pieces:
// src/App.jsx
import { useState } from "react";
import { useTodos } from "./TodosContext";
import AddTodoForm from "./AddTodoForm";
import TodoList from "./TodoList";
export default function App() {
const todos = useTodos();
const [filter, setFilter] = useState("all");
const remaining = todos.filter((todo) => !todo.done).length;
return (
<main>
<h1>To-do</h1>
<AddTodoForm />
<p>{remaining} remaining</p>
<select
aria-label="Filter"
value={filter}
onChange={(e) => setFilter(e.target.value)}
>
<option value="all">All</option>
<option value="active">Active</option>
<option value="completed">Completed</option>
</select>
<TodoList filter={filter} />
</main>
);
}The filter stays in App as local state. Only TodoList needs it, and it is one prop one level down. Not everything belongs in context.
// src/AddTodoForm.jsx
import { useState } from "react";
import { useTodosDispatch } from "./TodosContext";
export default function AddTodoForm() {
const dispatch = useTodosDispatch();
const [text, setText] = useState("");
function handleSubmit(event) {
event.preventDefault();
const title = text.trim();
if (!title) return;
dispatch({ type: "added", id: crypto.randomUUID(), title });
setText("");
}
return (
<form onSubmit={handleSubmit}>
<label>
New task
<input value={text} onChange={(e) => setText(e.target.value)} />
</label>
<button type="submit">Add</button>
</form>
);
}// src/TodoList.jsx
import { useTodos } from "./TodosContext";
import TodoItem from "./TodoItem";
export default function TodoList({ filter }) {
const todos = useTodos();
const visible = todos.filter((todo) => {
if (filter === "active") return !todo.done;
if (filter === "completed") return todo.done;
return true;
});
return (
<ul>
{visible.map((todo) => (
<TodoItem key={todo.id} todo={todo} />
))}
</ul>
);
}// src/TodoItem.jsx
import { useTodosDispatch } from "./TodosContext";
export default function TodoItem({ todo }) {
const dispatch = useTodosDispatch();
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => dispatch({ type: "toggled", id: todo.id })}
/>
<span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
{todo.title}
</span>
</label>
<button
type="button"
onClick={() => dispatch({ type: "deleted", id: todo.id })}
>
Delete
</button>
</li>
);
}TodoItem now takes one prop, the todo it displays. It gets the ability to change the list from context. TodoList forwards nothing.
How the data flows
Edge cases and gotchas
Every consumer re-renders when the value changes
When the provider's value changes, React re-renders every component that calls useContext for that context. This happens even if the component uses only a small part of the value. React compares the value with Object.is.
That is why the todos array and dispatch are separate contexts. It also explains a common mistake: passing a new object literal as the value.
// Re-creates the object on every render of the provider,
// so every consumer re-renders every time.
<TodosContext.Provider value={{ todos, dispatch }}>If you do need a combined object, wrap it in useMemo so its identity changes only when its contents do.
Re-rendering of the provider's children
If the provider's parent re-renders and passes new children elements, those children re-render as usual. In the setup above, TodosProvider re-renders when its own state changes. The children prop keeps the same identity, because it was created by main.jsx. So App itself re-renders only because it calls useTodos(). Passing the tree as children is the reason the provider doesn't force a full re-render.
Context does not replace props
Use props for data that one component hands to its direct child, such as todo in TodoItem. This keeps components easy to reuse and test. Use context for values that many components at different depths need, such as the current user, theme, or here, the list and its dispatch.
Where to put the provider
Place the provider as low in the tree as works. State kept high re-renders more of the app when it changes. For this app, the root is fine because nearly everything uses the list.
Testing
Tests that render a consumer in isolation must wrap it in the provider, or the hook throws your error message. In the earlier test, render(<App />) would fail now, so render <TodosProvider><App /></TodosProvider> instead. Alternatively, export a small renderWithProviders helper.
When to stop using context
Context is a good fit for the to-do list in a small app. It becomes harder to manage when many unrelated values change often, because every consumer re-renders on each change. At that point, split the state into more contexts, or look at a dedicated state library. For this app, one provider is enough.
Exercise
A teammate changes the provider to <TodosContext.Provider value={{ todos, dispatch }}> and removes the second context. The add form uses only dispatch. After typing nothing and toggling a checkbox elsewhere, will the add form re-render? Give the two reasons it does, and describe one change that fixes it.
Show answer
Yes, it re-renders. First, the object literal { todos, dispatch } is a new object on every provider render, so Object.is sees a changed value. Second, toggling a checkbox changes todos, which re-renders the provider. Every component that calls useContext on that context re-renders, including the add form, even though it only reads dispatch. Fix it by restoring a separate context for dispatch, since the dispatch function has a stable identity. Alternatively, keep one context but wrap the value in useMemo. That would still re-render the form whenever todos changes, so the split is the better fix.