Skip to main content
A protocol that describes how to evolve the current state of an application to the next state, given an action, and describes what effects should be executed later by the store, if any.

Protocol Definition

public protocol Reducer<State, Action> {
  associatedtype State
  associatedtype Action
  associatedtype Body
  
  var body: Body { get }
}

Associated Types

State
associatedtype
A type that holds the current state of the reducer.
Action
associatedtype
A type that holds all possible actions that cause the State of the reducer to change and/or kick off a side Effect that can communicate with the outside world.
Body
associatedtype
A type representing the body of this reducer. When you create a custom reducer by implementing the body property, Swift infers this type from the value returned. If you create a custom reducer by implementing reduce(into:action:), Swift infers this type to be Never.

Properties

body
some ReducerOf<Self>
The content and behavior of a reducer that is composed from other reducers. In the body of a reducer one can compose many reducers together, which will be run in order, from top to bottom.
Do not invoke this property directly. It is called by the Store.

Methods

reduce(into:action:)
(inout State, Action) -> Effect<Action>
Deprecated: Don’t invoke a reducer directly. Reducers are processed by the store. If you need to run a reducer on some child state given some child action, use a ‘send’ effect instead.

Usage

Define a reducer by conforming to the Reducer protocol and implementing the body property:
@Reducer
struct Feature {
  struct State: Equatable {
    var count = 0
  }
  
  enum Action {
    case incrementButtonTapped
    case decrementButtonTapped
  }
  
  var body: some ReducerOf<Self> {
    Reduce { state, action in
      switch action {
      case .incrementButtonTapped:
        state.count += 1
        return .none
        
      case .decrementButtonTapped:
        state.count -= 1
        return .none
      }
    }
  }
}

Composing Reducers

Reducers can be composed together in the body using reducer operations:
var body: some ReducerOf<Self> {
  Reduce { state, action in
    // Core logic
  }
  .ifLet(\.child, action: \.child) {
    ChildFeature()
  }
  ._printChanges()
  
  Analytics()
}

Type Aliases

ReducerOf
typealias
A convenience for constraining a Reducer conformance:
public typealias ReducerOf<R: Reducer> = Reducer<R.State, R.Action>
This allows you to specify the body of a Reducer conformance like:
var body: some ReducerOf<Self> {
  // ...
}
Instead of the more verbose:
var body: some Reducer<State, Action> {
  // ...
}

Build docs developers (and LLMs) love