React
Context + useReducer
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.
Exercise 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.
Show example 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;
Test yourself
-
What does useReducer return?
- [value, setValue]
- single value
- [state, dispatch]
- [data, error]
Show answer
[state, dispatch] — useReducer returns [state, dispatch].
-
Dispatch role
Dispatch sends the action object to the ____.
Show answer
Dispatch sends the action object to the reducer.
-
Match the useReducer + context steps
- useReducer
- [state, dispatch]
- StateContext
- holds state
- DispatchContext
- holds dispatch
- dispatch
- action
Next lesson: Default value and error