Skip to main content

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.

Reducer + Context responsibilities
FeatureProvider
OWNERuseReducer
owns feature state + transitions
READSState Context
distributes current state
WRITESDispatch Context
distributes stable dispatch

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?​

Read and write subscriptions can be different dependencies
State readers
Need current feature state and can re-render when it changes.
Dispatch-only components
Need the stable dispatch function, not the changing state object.

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});
}
}
External work surrounds the pure state machine
1UI event
2dispatch started
3async external work
4dispatch success/failure
5reducer records transition

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>
}
/>
Provider scope defines state scope
Provider too high
Longer lifetime Β· broader coupling Β· more unrelated consumers in the environment.
Feature-scoped provider
State lifetime and access align with the feature that owns it.

Multiple providers create multiple state instances​

<CartProvider>
<StorefrontA />
</CartProvider>

<CartProvider>
<StorefrontB />
</CartProvider>

These are two independent carts.

Context state is not inherently singleton/global
CartProvider A
owns cart state A
CartProvider B
owns cart state B

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.

Prefer reducers around coherent feature/state-machine boundaries
CartProvider
cartReducer
EditorProvider
editorReducer
CheckoutProvider
checkoutReducer

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​

Does the feature need more than reducer + Context provides?
One subtree, moderate updates, full-state subscriptions are fineReducer + Context is likely enough
Many distant roots / non-React code need the same ownerConsider an external store
High-frequency updates with independent selector subscriptions are importantConsider a store designed for fine-grained subscriptions
The difficult problem is server caching/invalidationUse a server-state architecture instead

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​

Reducer + Context feature dependency direction
UI components
Feature Hooks
Context + Provider
Reducer + domain helpers

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​

Reducer + Context decision sequence
1complex local feature transitions
2useReducer owns state machine
3Context distributes subtree access
4split read/write APIs when useful
5keep provider scope intentional
6external store only when requirements demand it

References​

Next​

Continue with State Architecture: Local, Shared, Server, and External State.