Skip to content

Middleware

ChiefVenzox edited this page Jun 5, 2026 · 1 revision

Middleware

Middleware runs before the reducer and can observe, transform, or delay action flow.

Built-in Logger

let store = Store(
    initialState: AppState(),
    reducer: appReducer,
    middlewares: [createLoggerMiddleware()]
)

The logger prints action names and before/after state snapshots in debug builds.

Custom Middleware

let analyticsMiddleware: Middleware<AppState> = { action, getState, dispatch, next in
    analytics.track(String(describing: action))
    next(action)
}

Middleware receives:

  • action: the current action
  • getState: read the current state
  • dispatch: dispatch a new action
  • next: continue to the next middleware or reducer

Best Practices

  • Always call next(action) unless you intentionally want to stop the action.
  • Use middleware for cross-cutting concerns such as analytics and logging.
  • Use Async Effects for feature-specific async work.
  • Keep middleware small and predictable.

Clone this wiki locally