Consumer-Provided Reducer Override
What you'll learn: How to let consumers pass their own reducer function to take full control over state transitions in your component or hook.
The Core Idea
In the State Reducer pattern, the consumer-provided reducer override is where the magic happens. Instead of being stuck with your component's default state management logic, consumers can pass their own reducer function that intercepts every state change and decides what actually happens.
Think of it like customizing the rules of a board game. You provide the standard rulebook (default reducer), but players can bring their own house rules (custom reducer) that override or modify specific moves while keeping the rest intact.
How It Works
Your component receives an optional reducer prop. When a state change occurs:
- Your component calls the consumer's reducer with the current state, action, and any changes you were planning to make
- The consumer's reducer decides what to actually return—they can approve your changes, modify them, or block them entirely
- The final state becomes whatever the consumer's reducer returned
// Consumer's custom reducer
function myReducer(state, action, changes) {
// Block toggling on when already disabled
if (action.type === 'toggle' && state.isDisabled) {
return state; // No change!
}
// Otherwise accept default behavior
return changes;
}
// Using it
<Toggle reducer={myReducer} />
The consumer gets complete veto power over state transitions. They can inspect the action type, current state, and your proposed changes before deciding what actually happens.
Why This Matters
This gives consumers surgical control without forking your component. They can implement complex business logic (like "can't enable during loading"), audit state changes, or add validation—all without touching your code.
Key Takeaway: Consumer-provided reducer overrides transform your component from "this is how it works" to "this is how it works by default"—the ultimate flexibility escape hatch.