AceDevHub
Intermediate React Interview QuestionsIntermediateConcept

React · Question 40

What makes a well-designed reducer in React?

Direct answer

A reducer should be a pure function that receives the current state and an action, then returns the next state without mutating the previous state or performing side effects.

tasksReducer.js
function tasksReducer(state, action) {
  switch (action.type) {
    case "added":
      return [
        ...state,
        { id: action.id, text: action.text, done: false }
      ];
    case "toggled":
      return state.map(task =>
        task.id === action.id
          ? { ...task, done: !task.done }
          : task
      );
    default:
      return state;
  }
}
  • Pure transition: same state + action should produce the same next state.
  • No side effects: API calls, analytics, timers, and DOM work belong outside the reducer.
  • Action intent: actions should describe meaningful events such as added or toggled rather than hide arbitrary mutations.