Sub topic 14
Sharing state with context
This chapter assumes you have lifted the to-do state into App and moved its update logic into todosReducer, as in the previous chapters. You should also be comfortable with props and with useReducer.
The problem: prop drilling
App owns the todos array and the handlers. Right now App passes onToggle and onDelete to TodoList, which passes them on to every TodoItem. TodoList never calls these functions. It only forwards them. This is called prop drilling. It is harmless in a small app, but each new layer of components has to forward the same props again.
Context lets a component read shared state directly, without receiving it through every parent in between.
Creating the context
Use two contexts: one for the todos array and one for dispatch. The dispatch function never changes between renders, so components that only send actions will not re-render when the list changes.
import { createContext, useContext, useReducer } from "react";
import { todosReducer } from "./todosReducer";
const TodosContext = createContext(null);
const TodosDispatchContext = createContext(null);
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;
}The default value null and the checks in the hooks turn a forgotten provider into a clear error message. Without them, you would get a confusing undefined failure later.
This file assumes todosReducer is exported from todosReducer.js. Move the reducer from the previous chapter there and add export to it.
Providing it once
Wrap the app at the top, usually in 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>
);Consuming it
TodoItem no longer needs onToggle or onDelete. It gets dispatch itself and receives only the todo to display:
import { useTodosDispatch } from "./TodosContext";
export 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>
);
}TodoList now only needs useTodos() for the array, or the already filtered list as a prop.
Common errors
- Using the hook outside the provider. This throws the error you wrote above. Check that the component is rendered inside
TodosProvider. - Passing a new object as
value. A value likevalue={{ todos, dispatch }}is a new object on every render. Every consumer re-renders each time the provider does. Passing the two values separately avoids this. - Reaching for context too early. Context hides where data comes from. Two levels of props are fine. Use context when the same state is needed in many places or deep in the tree.
Exercise
Why does the chapter use two contexts, one for todos and one for dispatch, instead of one context holding both?
Show answer
React guarantees that dispatch keeps the same identity between renders, so components that only call dispatch (such as a delete or add control) do not re-render when todos changes. With one combined context, every consumer would re-render on each list change, and a freshly created { todos, dispatch } object would also trigger re-renders on every provider render.