Sub topic 12
Splitting contexts to limit re-renders
This chapter assumes you know createContext, Provider and useContext, and that you have seen why a changed context value re-renders every consumer. It also assumes you have used useReducer with context.
Why one context can be too coarse
Every component that calls useContext(SomeContext) re-renders when that context's value changes. React compares the old and new values with Object.is. React does not check which part of the value a component actually uses.
Suppose one context holds { tasks, dispatch }. A form that only calls dispatch still re-renders on every task change, because the object holding both fields changed. The form does not need the new data, so the render is wasted.
Split by who needs what
Put values that change often in one context. Put values that rarely change in another. A good first split is state in one context and dispatch in the other. React guarantees that dispatch from useReducer keeps the same identity between renders, so the dispatch context never changes.
import { createContext, useContext, useReducer } from 'react';
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);
function tasksReducer(tasks, action) {
switch (action.type) {
case 'added':
return [...tasks, { id: action.id, text: action.text, done: false }];
case 'toggled':
return tasks.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
default:
throw new Error('Unknown action: ' + action.type);
}
}
export function TasksProvider({ children }) {
const [tasks, dispatch] = useReducer(tasksReducer, []);
return (
<TasksContext.Provider value={tasks}>
<TasksDispatchContext.Provider value={dispatch}>
{children}
</TasksDispatchContext.Provider>
</TasksContext.Provider>
);
}
export function useTasks() {
return useContext(TasksContext);
}
export function useTasksDispatch() {
return useContext(TasksDispatchContext);
}Now write two consumers. Each one subscribes only to what it uses.
import { useState } from 'react';
import { TasksProvider, useTasks, useTasksDispatch } from './tasks';
let nextId = 1;
function AddTask() {
const dispatch = useTasksDispatch();
const [text, setText] = useState('');
console.log('AddTask rendered');
return (
<form
onSubmit={(e) => {
e.preventDefault();
dispatch({ type: 'added', id: nextId++, text });
setText('');
}}
>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button type="submit">Add</button>
</form>
);
}
function TaskList() {
const tasks = useTasks();
return (
<ul>
{tasks.map((t) => (
<li key={t.id}>{t.text}</li>
))}
</ul>
);
}
export default function App() {
return (
<TasksProvider>
<AddTask />
<TaskList />
</TasksProvider>
);
}Adding a task changes the tasks value. TaskList re-renders. AddTask does not re-render because of context. It re-renders only when you type, because its own text state changes.
Common errors
- Splitting too early. Each extra context adds a provider and a hook. Split only when you can point to a component that re-renders for no reason.
- Passing
childrenincorrectly. The provider keeps children from re-rendering only becausechildrenis a prop whose elements come from the parent. If you create child elements inside the provider's own render, they are new objects every time the provider's state changes, and they re-render. - Splitting by data type instead of change rate. Separating "user" from "theme" helps only if they change at different times or are read by different components.
- Assuming a split stops parent-driven renders. If a parent re-renders and passes new props, children still re-render. Context splitting affects only context-driven renders.
Exercise
A ThemeContext value is { theme, fontSize }. A component reads only theme. Does it re-render when fontSize changes, and how would you prevent that?
Show answer
Yes. The value is a new object, so every consumer re-renders, even one that reads only theme. Split it into a ThemeContext for theme and a FontSizeContext for fontSize, so the component subscribes only to ThemeContext.