Reducers centralize transitions when related fields must change together. Actions describe intent, and pure reducers preserve the model’s invariants.
Before you start
You should know how a function component renders JSX, receives props and handles events. Follow the value through render, interaction and the next render. Small snippets below belong inside an existing React application unless they are explicitly shown as complete components.
The practical goal is to reason through this situation: A checkout action can clear an old error while entering a submitting state. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Write permitted states
Use editing, submitting and failure states instead of unrelated loading and error flags that allow contradictory combinations.
Step 2: Express actions as intent
Submit clears the old error and enters submitting together. Failure carries the new error; retry follows an explicitly allowed transition.
Step 3: Keep reduction pure
Return a new state without mutating previous state or performing a request. The action handler initiates the request and dispatches its outcome.
Worked scenario
A checkout action can clear an old error while entering a submitting state.
function reducer(state, action) {
switch (action.type) {
case 'submit': return { status: 'submitting', error: null };
case 'failed': return { status: 'failure', error: action.error };
case 'reset': return { status: 'editing', error: null };
default: return state;
}
}This minimal example centralizes related fields. A production reducer should additionally reject actions that are invalid for its current state rather than assuming every action sequence is permitted.
Common mistake
Mutating previous state can prevent expected identity changes and obscure debugging.
Verify the behavior
Trace submit, failure and retry. Assert the old error disappears on retry and decide how late responses from a previous submission are identified.
Interview exercise
Represent submission failure.
Answer and reasoning
Return a failure state carrying its error and permitted retry transition; do not scatter independent flags across handlers.
Continue learning
Compare the scenario with the React interview questions and test your understanding with the React MCQs. For terminology and implementation details, consult the reference material.