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

The Basic State Reducer API

Exposing a reducer prop that lets consumers intercept and modify state updates before they're applied.

The Basic State Reducer API

You'll learn how to expose a reducer prop that lets consumers intercept and modify your component's state updates before they're applied.

The Core Idea

Remember how the State Reducer Pattern solves the problem of users needing custom state logic? The basic API is simple: your component accepts a reducer function as a prop. Before applying any internal state change, you call this user-provided reducer, giving them a chance to modify, override, or even block the update.

Think of it like a security checkpoint: every state change must pass through the user's reducer function before being applied. If they don't provide one, your component uses its default logic.

How It Works

Your component maintains internal state with useReducer. When a state change occurs, you dispatch an action through the user's reducer (if provided) before updating:

function useToggle({
  reducer = (state, action) => action.changes // default: accept all changes
} = {}) {
  const internalReducer = (state, action) => {
    const changes = getChangesForAction(state, action);
    
    // Pass through user's reducer
    return reducer(state, { ...action, changes });
  };

  const [state, dispatch] = useReducer(internalReducer, { on: false });
  // ...
}

The user receives both the current state and an action object containing proposed changes. They can return those changes as-is, modify them, or return completely different state.

The Handshake

You provide: current state + proposed changes.
They return: final state to apply.

This creates a before-apply hook where consumers gain full control over state transitions while you handle all the complexity of determining what should change.

Key Takeaway: The basic state reducer API is a function prop that receives current state and proposed changes, returning the final state to apply—giving users an interception point for every state update.