Course contentsShow
← React
Lesson 1179 of 2,39630. Composition: Inversion of ControlFree lesson

Combining Consumer and Default Reducers

Letting consumer reducers delegate back to the default reducer for standard behavior.

Combining Consumer and Default Reducers

What you'll learn: How to let consumers customize state changes while preserving default behavior through reducer composition.

The Power of Delegation

You've learned how consumers can provide their own reducer to customize state logic. But what if they only want to override some actions, not all of them? Forcing consumers to reimplement every action would be tedious and error-prone.

The solution: let the consumer reducer delegate back to your default reducer for any action they don't want to customize.

How Delegation Works

Pass your default reducer to the consumer's reducer as an argument. Now the consumer can choose:

  • Override: Handle the action themselves and return custom state
  • Delegate: Call your default reducer and return its result
  • Enhance: Call your default reducer, then modify the result before returning

Think of it like a chain of command: the consumer gets first choice, but can always say "handle this the normal way" by calling your default reducer.

The Pattern in Practice

function useCustomToggle(reducer) {
  const defaultReducer = (state, action) => {
    // your default logic
  };

  const combinedReducer = (state, action) => {
    // Consumer gets first chance
    return reducer(state, action, defaultReducer);
  };

  return useReducer(combinedReducer, initialState);
}

// Consumer usage:
const myReducer = (state, action, defaultReducer) => {
  if (action.type === 'SPECIAL_CASE') {
    return { isOn: false }; // Custom behavior
  }
  return defaultReducer(state, action); // Delegate everything else
};

The consumer only customizes what they need; everything else flows through your default implementation.

Key Takeaway: Passing the default reducer as a third argument to the consumer's reducer enables selective customization—consumers override specific actions while delegating the rest back to your battle-tested defaults.