React › useReducer & Complex State Logic

What is the basic structure of a reducer function used with the useReducer hook?

Intermediate

Answer

A reducer is a plain function that takes the current state and an action describing what happened, and returns the new state based on that action. It should never directly change the existing state, but instead always return a brand new state object reflecting the update.
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

const [state, dispatch] = useReducer(reducer, { count: 0 });
Real-world example A counter component uses a simple reducer with increment and decrement actions, keeping all the logic for how the count changes clearly organized in one single function instead of scattered across multiple event handlers.

Common follow-ups: What happens if a reducer receives an action type it does not recognize?;Why should a reducer always return a brand new object instead of modifying the existing state directly?