Reducer + Context architecture
Reducers centralize state transition logic. Context distributes access through a subtree.
Together they can form a lightweight feature-state architecture when many descendants need one coherent client-owned state machine.
Start with local reducer stateβ
Do not introduce Context just because you use a reducer.
function CheckoutPage() {
const [state, dispatch] = useReducer(checkoutReducer, initialState);
return <CheckoutForm state={state} dispatch={dispatch} />;
}
If a small part of the tree needs the data, props may be the clearest API. Context becomes useful when many descendants need the same state/dispatch through otherwise unrelated intermediate layers.
The feature provider patternβ
const CartStateContext = createContext(null);
const CartDispatchContext = createContext(null);
export function CartProvider({children}) {
const [state, dispatch] = useReducer(cartReducer, initialCartState);
return (
<CartStateContext value={state}>
<CartDispatchContext value={dispatch}>
{children}
</CartDispatchContext>
</CartStateContext>
);
}
Consumers can expose feature-specific read/write Hooks:
export function useCartState() {
const state = useContext(CartStateContext);
if (state === null) throw new Error('useCartState must be used inside CartProvider');
return state;
}
export function useCartDispatch() {
const dispatch = useContext(CartDispatchContext);
if (dispatch === null) throw new Error('useCartDispatch must be used inside CartProvider');
return dispatch;
}
Why split state and dispatch?β
This improves API clarity and can avoid making dispatch-only components depend on the changing state context.
Keep reducer logic outside the providerβ
A provider should compose ownership/distribution, not become a 500-line transition engine.
Literal feature structure can remain simple:
cart/
CartProvider.jsx
cartReducer.js
useCartState.js
useCartDispatch.js
The goal is separation of responsibility, not maximum file count.
Reducer purity does not changeβ
Combining a reducer with Context does not permit network requests, storage writes, analytics, timers, DOM effects, or mutation inside the reducer.
function cartReducer(state, action) {
switch (action.type) {
case 'item_added':
return addItem(state, action.product);
default:
throw new Error(`Unknown cart action: ${action.type}`);
}
}
Async workflows stay outside the reducerβ
async function handleCheckout() {
dispatch({type: 'submission_started'});
try {
const order = await createOrder(state);
dispatch({type: 'submission_succeeded', orderId: order.id});
} catch (error) {
dispatch({type: 'submission_failed', message: error.message});
}
}
Selectors centralize derivationβ
export function selectCartTotal(state) {
return state.items.reduce(
(total, item) => total + item.price * item.quantity,
0,
);
}
Selectors centralize domain calculations, but reading a selector from Context does not create a fine-grained context subscription. The component still reads the state Context value.
Domain commands as custom Hooksβ
Consumers do not always need to know raw action shapes.
export function useCartActions() {
const dispatch = useCartDispatch();
return {
addItem(product) {
dispatch({type: 'item_added', product});
},
removeItem(productId) {
dispatch({type: 'item_removed', productId});
},
};
}
This can create a stronger feature API. Do not add wrappers mechanically; use them when they improve domain meaning or API stability.
Provider boundaries are part of state architectureβ
Bad default:
<CartProvider>
<EntireCompanyWebsite />
</CartProvider>
Better when only shop routes need cart state:
<Route
path="/shop/*"
element={
<CartProvider>
<Shop />
</CartProvider>
}
/>
Multiple providers create multiple state instancesβ
<CartProvider>
<StorefrontA />
</CartProvider>
<CartProvider>
<StorefrontB />
</CartProvider>
These are two independent carts.
This can be useful for tests, previews, embedded widgets, and multi-instance features.
Reset by provider identityβ
<CartProvider key={storeId}>
<Storefront storeId={storeId} />
</CartProvider>
Changing the key changes component identity, so React can create a fresh reducer state instance. Use this intentionally when identity should reset the whole feature owner.
Avoid one reducer for the whole applicationβ
A universal reducer owning auth, cart, notifications, editor, theme, billing, and unrelated dashboard state usually creates excessive coupling.
When reducer + Context is enoughβ
This architecture is a strong fit when:
- state is client-owned;
- one coherent feature subtree needs it;
- transition logic benefits from a reducer;
- many descendants need access;
- update frequency is moderate;
- full-context state subscriptions are acceptable.
When to consider an external storeβ
Context + reducer is not Reduxβ
The concepts overlapβactions, reducer, dispatch, stateβbut useReducer + Context does not automatically provide middleware, selector subscription infrastructure, Redux DevTools integration, normalized-store conventions, or global singleton semantics.
Use the smallest architecture that solves the actual requirements.
Testingβ
Test the pure reducer directly for transition rules, then test provider integration through visible user behaviour.
render CartProvider + UI
click Add
assert visible cart count
This literal test recipe is clearer as text than as a diagram.
Dependency directionβ
Exerciseβ
Build a ProjectProvider with useReducer, separate state/dispatch contexts, read/write Hooks, rename/task actions, reset, and a completion-percentage selector. Identify which components need state, which only need dispatch, and where the provider belongs.
Interview questionsβ
Mid-level: Why combine a reducer with Context?
Senior: Why might you split state and dispatch into separate contexts?
Staff: What evidence would make you replace reducer+Context with an external store, and what trade-offs would the migration introduce?
Summaryβ
Referencesβ
- https://react.dev/learn/scaling-up-with-reducer-and-context
- https://react.dev/learn/extracting-state-logic-into-a-reducer
- https://react.dev/reference/react/useReducer
- https://react.dev/reference/react/useContext
Nextβ
Continue with State Architecture: Local, Shared, Server, and External State.