Lesson 2 · Unit 04
Context and reducers
Skip prop drilling with context, and keep state with rules in a reducer.
What you practise
- Prop drilling, context for values many components read,
useReducerfor state with rules
Try a question from this lesson
Pick one
Two providers, one inside the other. What HTML does this render?
const Theme = createContext('light');
function Label() {
return <i>{useContext(Theme)}</i>;
}
const out = (
<Theme value="dark">
<Label />
<Theme value="pink">
<Label />
</Theme>
</Theme>
);Correct answer
<i>dark</i><i>pink</i>
Why
A component reads the nearest provider above it in the tree. The first label has only the outer provider above it. The second sits inside the inner one, which overrides the outer for its own subtree.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Context
Context lets a parent offer a value to every component below it, however deep, without props. createContext(default) makes the channel, the provider tag sets the value for a subtree, and useContext reads the nearest provider above. From React 19 the context itself is the provider tag; older code writes <Theme.Provider>.
const Theme = createContext('light');
function Button() {
return <b>{useContext(Theme)}</b>;
}
const app = (
<Theme value="dark">
<Button />
</Theme>
);Concept
useReducer
When state has rules (several kinds of update, each with conditions), collect them in one reducer. The component stops saying how to change state; it dispatches an action that says what happened. React calls the reducer with the current state and the action, stores the result and re-renders. A reducer must be pure.
const [n, dispatch] =
useReducer(reducer, 0);
// in a handler:
const onAdd = () =>
dispatch({ type: 'add' });9 more exercises in the app
- 4× type the answer
- 1× true or false
- 1× fill the blanks
- 2× multiple choice
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.