Reducer Function: (state, action) => newState
You'll learn the fundamental signature of a reducer function and what makes it the right tool for managing complex state transitions.
What is a Reducer Function?
A reducer is a pure function that takes two arguments—the current state and an action object—and returns the next state. It never modifies the current state directly; instead, it computes and returns a brand new state object based on the action.
The signature looks like this:
(state, action) => newState
Think of it like a state machine operator: given "what we have now" (state) and "what happened" (action), it determines "what we should have next" (newState).
Why This Pattern?
Instead of scattering state updates across multiple useState setters and event handlers, you centralize all state transition logic in one place. The reducer becomes the single source of truth for how state can change.
The action object typically has a type property describing what happened (like 'increment', 'reset', or 'field_updated'), plus any additional data needed to perform the update.
The Pure Function Requirement
Just like you've learned with React components, reducers must be pure:
- Same inputs always produce same output
- No side effects (no API calls, no mutations)
- Returns a new object/array rather than modifying the original
This predictability makes state transitions testable, debuggable, and easier to reason about. You can pass the same state and action through your reducer 100 times and get identical results every time.
Key Takeaway: A reducer is a pure function (state, action) => newState that centralizes state transition logic, making complex state updates predictable and maintainable.