Reducers, context, and state ownership
Make state transitions explicit, distribute only the state that needs sharing, and preserve a server-rendered outer page.
What you will be able to do
- Design actions around user intent and enforce invariants in one reducer.
- Separate reducer logic from context-based distribution.
- Choose provider placement and persistence from product requirements.
Before this lesson
Describe events before choosing a library
A ballot has categories and nominees. The user can select one nominee in a category, clear one category or reset the ballot. Start by listing these events and the legal next state for each. The important invariant is one current selection per category. Representing selection as a category-to-nominee map makes that invariant easier to preserve than maintaining an isSelected flag on every nominee.
A reducer is a function from current state and action to next state. It centralizes transition rules that would otherwise be scattered across click handlers. It should not fetch, write storage, generate random IDs or depend on the current clock. Pass needed information in the action. This makes replay and testing possible, but a reducer is not automatically a global store, a network cache or a persistence layer. Those are separate responsibilities.
Design actions that retain the user intention
Prefer an action such as select with categoryId and nomineeId over a vague action that replaces arbitrary internal fields. The reducer can validate that the nominee belongs to the category before accepting it. A malformed event should have a documented result. The kata chooses to ignore invalid categories, invalid nominees and unknown actions. Throwing can also be appropriate for impossible developer mistakes, but silently accepting corrupt selection data is not.
Keep transitions immutable. Returning a new map after a valid selection preserves the old snapshot for components and tests. A repeated selection may produce the same domain result, which is useful when events are retried or controls are activated twice. Distinguish this client idempotence from a server guarantee: executing the same HTTP mutation twice can still have side effects unless the server contract also handles repetition.
Shared application logic
type State = Record<string, string>;
type Action =
| { type: 'select'; categoryId: string; nomineeId: string }
| { type: 'clear'; categoryId: string }
| { type: 'reset' };
export function reducer(state: State, action: Action): State {
if (action.type === 'reset') return {};
if (action.type === 'select') {
return { ...state, [action.categoryId]: action.nomineeId };
}
const next = { ...state };
delete next[action.categoryId];
return next;
}Use context to distribute a well-defined value
Context solves access through a component tree: descendants can read a provider value without every intermediate component forwarding it. It does not decide how that value changes. Combining useReducer with context is therefore a composition of two ideas: transition logic and distribution. For a tiny parent with two children, direct props may be clearer. Introduce context when multiple distant consumers actually need the same state.
Provider scope determines ownership and lifetime. A cart provider around the relevant application section can survive sibling navigation if its layout remains mounted. Putting a fresh provider in every page can reset the cart. Placing every transient input in the root provider broadens updates and hides dependencies. Separating state and dispatch contexts can keep dispatch-only consumers independent of state value changes, but optimize only after understanding which consumers rerender.
Compose providers inside a server-rendered layout
The provider that uses hooks is a Client Component. A Server Component layout can render that provider and pass server-rendered children through it. The client provider does not need to import the server data-loading page. This is composition across a module boundary: the server constructs children, and the client wrapper controls interaction around them. Keep the provider as deep as its consumers allow so unrelated parts of the app avoid unnecessary client dependencies.
For durable or shared state, specify the source of truth. Context disappears on a fresh document load unless it is initialized from storage or server data. Browser storage introduces hydration and synchronization concerns; a server cart introduces identity, authorization and concurrency concerns. Do not hide these differences behind the word global. In the interview, name the state owner, who can change it, how long it survives, and which behavior proves that requirement.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEContext replaces reducer logic and server-state caching.
- A more accurate model
Context distributes a value; a reducer defines transitions; a query cache manages remote representations. They solve distinct problems.
- How to check it
R03 and R04 describe reducer logic and context distribution separately.
- CLAIM TO CHALLENGEPutting a client provider around children requires importing all child server modules into it.
- A more accurate model
The server can construct children and pass their rendered representation through the provider. Module imports and rendered composition are different graphs.
- How to check it
N06 documents interleaving Server and Client Components and provider placement.
Mistakes to catch in your own code
- Context does not automatically persist data across reloads or devices.
- Do not perform network requests or storage writes inside a reducer.
- Do not import a server-only data module into the provider’s client module graph.
Write it by hand
JavaScript logic playground
Reduce a valid ballot
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Implement solve({categories, actions}). Categories have unique IDs and nominee ID arrays. Begin with no selections.
- select replaces the category selection only if that nominee belongs to the category. clear removes the named category. reset removes every selection. Unknown or invalid actions have no effect.
- Return an object mapping selected category IDs to nominee IDs. IDs are ordinary nonempty strings. The browser exercise models transitions only.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- One selection per category
Input
{ "categories": [ { "id": "film", "nominees": [ "a", "b" ] }, { "id": "music", "nominees": [ "c" ] } ], "actions": [ { "type": "select", "categoryId": "film", "nomineeId": "a" }, { "type": "select", "categoryId": "film", "nomineeId": "b" }, { "type": "select", "categoryId": "music", "nomineeId": "c" } ] }Expected
{ "film": "b", "music": "c" } - Invalid nomination cannot leak across categories
Input
{ "categories": [ { "id": "film", "nominees": [ "a" ] }, { "id": "music", "nominees": [ "b" ] } ], "actions": [ { "type": "select", "categoryId": "film", "nomineeId": "b" }, { "type": "select", "categoryId": "missing", "nomineeId": "a" } ] }Expected
{} - Clear preserves unrelated selection
Input
{ "categories": [ { "id": "a", "nominees": [ "1" ] }, { "id": "b", "nominees": [ "2" ] } ], "actions": [ { "type": "select", "categoryId": "a", "nomineeId": "1" }, { "type": "select", "categoryId": "b", "nomineeId": "2" }, { "type": "clear", "categoryId": "a" } ] }Expected
{ "b": "2" } - Reset and restart
Input
{ "categories": [ { "id": "a", "nominees": [ "1" ] } ], "actions": [ { "type": "select", "categoryId": "a", "nomineeId": "1" }, { "type": "reset" }, { "type": "unknown" } ] }Expected
{}
Reveal the worked solution and reasoning
function solve(input) {
const allowed = new Map(input.categories.map(category => [category.id, new Set(category.nominees)]));
let selected = new Map();
for (const action of input.actions) {
if (action.type === 'reset') selected = new Map();
else if (action.type === 'clear') selected.delete(action.categoryId);
else if (action.type === 'select' && allowed.get(action.categoryId)?.has(action.nomineeId)) {
selected.set(action.categoryId, action.nomineeId);
}
}
return Object.fromEntries(selected);
}A map models exactly one value per category. Membership validation rejects invalid events before changing the model.
The implementation uses a private mutable Map inside solve; no caller-owned state is mutated. A React reducer would return a new state snapshot for each transition.
Verify it in a real Next.js application
Next.js application lab
Test the shipped provider lifetime deliberately
Open the local application route /cart after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Trace the existing cartReducer through CartProvider in app/layout.tsx to AddToCart and the cart page. Identify which module owns transitions and which component owns the lifetime.
- Add a product, navigate between /catalog/keyboard and /cart, then reload. Explain why navigation preserves the mounted provider while a reload creates a new provider and restores its saved contents later.
- Add a temporary, nonpersisted counter inside CartProvider. Compare its value after sibling navigation and a full reload, so storage restoration cannot hide the lifetime difference.
- As an explicit extension, add a reset action and a labeled reset control. Implement the transition in the reducer, test it without mutating the previous lines, and confirm that persistence then records the empty cart.
Check the behavior
- Sibling navigation preserves the existing provider-owned state.
- The temporary counter resets after a full reload even when the cart is restored from storage.
- Server Components render the client provider without importing browser state hooks into server-only helpers.
- If the reset extension is implemented, it resets the complete line model and remains empty after restoration.
Review the application reasoning
Reducer and context wiring are already shipped. The experiment changes one observable state lifetime at a time rather than rebuilding the provider as if it were absent.
Remove the temporary counter after recording the result. Provider placement and persistence are separate decisions even when the final screen looks the same.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01What is the difference between a reducer and context?
A reducer defines how an event changes state. Context distributes a value to descendants. They can be used separately or together. I choose a reducer when several events must preserve shared invariants, and context when distant consumers need the result. Neither is a replacement for a server-state cache or durable database.
Follow-up questions
- When are props sufficient?
- Where would a storage write happen?
- React: extracting state logic into a reducerOfficial documentation
- React: scaling up with reducer and contextOfficial documentation
02Where would you place a cart provider in App Router?
At the lowest shared layout that must preserve the cart across the intended routes. The provider is a Client Component; the layout can remain a Server Component and pass children through it. I then test navigation and reload separately, because preserving a mounted provider does not make its state durable across a new document.
Follow-up questions
- What changes if the provider is inside page.tsx?
- How would initial server cart data reach the provider?
- Server and Client ComponentsOfficial documentation
- Layouts and pagesOfficial documentation
- React: scaling up with reducer and contextOfficial documentation
03What would you test in the ballot reducer?
I would test replacing a selection within one category, independent selections in different categories, clearing, reset, invalid category/nominee pairs and input immutability. These cases test the invariant and boundary contract. A test that merely asserts dispatch was called does not establish that the resulting selection is valid.
Follow-up questions
- How should unknown actions behave?
- How does a repeated event differ from duplicate server submission?
- Master Ventures interactive ballot assignmentEmployer assignment
- React: extracting state logic into a reducerOfficial documentation
04Does every shared value need a global state library?
No. A URL is often the correct owner for shareable filters, a data client owns remote query state, and local state owns a temporary open menu. I introduce a store only when its subscriptions, update model or cross-tree access solve a concrete need. First I separate these categories so one global object does not become several conflicting sources of truth.
Follow-up questions
- Where does a selected product ID belong?
- How do you distinguish a draft from server data?
- React: choosing the state structureOfficial documentation
- React: scaling up with reducer and contextOfficial documentation
- CompleteFrontend Next.js question bankPublisher practice bank
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- React: choosing the state structureOfficial documentation
- React: extracting state logic into a reducerOfficial documentation
- React: scaling up with reducer and contextOfficial documentation
- Layouts and pagesOfficial documentation
- Server and Client ComponentsOfficial documentation
- Master Ventures interactive ballot assignmentEmployer assignment
- Reusable searchable-select assignmentEmployer assignment