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

State Reducer in Downshift

Studying Downshift's stateReducer implementation as the canonical real-world example.

State Reducer in Downshift

What you'll learn: How Downshift, the industry-standard combobox library, implements the state reducer pattern to give consumers ultimate control over its behavior.

Downshift: The Real-World Reference

Downshift by Kent C. Dodds is the canonical example of the state reducer pattern in production React code. It's a library for building autocomplete, dropdown, and combobox components—complex UI that involves intricate state management (open/closed, highlighted index, selected item, input value).

How Downshift Uses State Reducers

Downshift exposes a stateReducer option in its hook (or component API). Here's the signature:

useCombobox({
  items,
  stateReducer: (state, actionAndChanges) => {
    // Return the next state
  }
})

The actionAndChanges object contains:

  • type: The action type (e.g., InputKeyDownEnter, ItemClick)
  • changes: Downshift's proposed state changes

The Real Power: Surgical Overrides

Want to prevent closing the menu when an item is selected? Override just that:

stateReducer: (state, { type, changes }) => {
  if (type === useCombobox.stateChangeTypes.ItemClick) {
    return {
      ...changes,
      isOpen: true  // Keep it open!
    }
  }
  return changes
}

This lets consumers modify any aspect of Downshift's behavior without forking the library or touching internal code.

Why It's the Gold Standard

Downshift handles dozens of state transitions (keyboard navigation, blur events, mouse interactions). The state reducer gives consumers an escape hatch for every single one without sacrificing Downshift's default smart behavior.

Key Takeaway: Downshift's stateReducer is the real-world proof that state reducers enable powerful customization in complex components—study its implementation and API design to master this pattern in your own libraries.