Context + useReducer
- React course
- Intermediate
- Lesson 10/80
- 4 min
Learn to manage a global useReducer state through context.
Context + useReducer
For large state, useState falls short. The useReducer + context combo is a classic pattern for global state management. It produces a Redux-like structure.
The shape: const [state, dispatch] = useReducer(reducer, initial);. Then wrap with <StateContext.Provider value={ '{ state }' }><DispatchContext.Provider value={ '{ dispatch }' }>...</DispatchContext.Provider></StateContext.Provider>.
Keeping state and dispatch in separate contexts means components using only dispatch don't react to state changes. This is the same performance tip from the previous lesson.
Nested Providers
Nesting two contexts is a common pattern. Outer StateContext.Provider, inner DispatchContext.Provider. Both share the result of the same useReducer call.
Wrapping order doesn't matter, but for readability state first then dispatch is recommended. Consumers read whichever context they want independently.
This pattern lets any part of the tree call dispatch({ '{ type: "ADD" }' }). Since the reducer is the single place that changes state, the flow stays predictable.
Practice Write AppProvider
Complete the skeleton. Write an AppProvider component. Call useReducer(reducer, initialState); destructure as [state, dispatch]. Return <StateContext.Provider value={ '{ state }' }> wrapping <DispatchContext.Provider value={ '{ dispatch }' }>...</DispatchContext.Provider></StateContext.Provider>; children come from the children prop. Export it.
Starter code
// Write the AppProvider component hereSample solution
function AppProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>
{children}
</DispatchContext.Provider>
</StateContext.Provider>
);
}
export default AppProvider;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does useReducer return?
- [value, setValue]
- single value
- [state, dispatch] Correct answer
- [data, error]
Explanation: useReducer returns [state, dispatch].
2 Dispatch role
Dispatch sends the action object to the ____.
Dispatch sends the action object to the reducer.
Explanation: Dispatch sends the action to the reducer.
3 Match the useReducer + context steps
| Term | Meaning |
|---|---|
useReducer |
[state, dispatch] |
StateContext |
holds state |
DispatchContext |
holds dispatch |
dispatch |
action |