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

Default Reducer Implementation

Creating a default reducer function that handles all standard state transitions internally.

Default Reducer Implementation

What you'll learn: How to build the internal reducer function that handles all state transitions before user customization.

The Foundation of State Reducer Pattern

When implementing the state reducer pattern, you need a default reducer that defines how your component's state naturally behaves. This is the reducer that runs before (or as a fallback to) any user-provided custom reducer.

Think of it like a car's standard controls: the default reducer is the factory-installed steering and acceleration logic. Users can customize how those controls behave, but they need a working baseline first.

Core Structure

Your default reducer handles all the action types your component supports internally:

function defaultReducer(state, action) {
  switch (action.type) {
    case 'TOGGLE':
      return { ...state, isOpen: !state.isOpen };
    case 'OPEN':
      return { ...state, isOpen: true };
    case 'CLOSE':
      return { ...state, isOpen: false };
    default:
      return state;
  }
}

This reducer lives inside your custom hook or component. It defines every state transition your component can perform. When users provide their own reducer later, they can choose to keep these defaults, modify them, or completely override them.

Why It Matters

Without a solid default reducer, users would have to implement every action from scratch, defeating the purpose of your reusable component. The default reducer does the heavy lifting; the custom reducer just tweaks what needs tweaking.

You'll later pass this default reducer to useReducer, and conditionally wrap it with user customization logic. But first, the defaults must work perfectly on their own.

Key Takeaway: The default reducer implements your component's complete natural behavior—every action type and state transition—providing the baseline that users can optionally customize.