skip to content

In a SwiftUI checkout screen built as a unidirectional store on Observation, why does every view re-run body on each action, and how do you narrow it?

level: seniorimportance: should knowfreq 35%

answer

  1. what Observation tracks: stored properties
  2. one struct, one key path
  3. inout mutation always notifies
  4. split state or scope child stores

basics

~20 s

Observation tracks the store's stored properties, so a single state struct is one tracked key path: any action that mutates any field notifies every view that read any part of it. Split state into separate stored properties or scoped child stores.

solid answer

~50 s

In a unidirectional store, views read `store.state` and send actions to `send(_:)`, which runs a reducer and starts effects. The `@Observable` macro instruments the store's stored properties, so `private(set) var state: CheckoutState` is one tracked property: a view that reads `state.total` depends on all of `state`. The reducer changes fields in place, through the macro's modify accessor, which notifies observers of `state` without comparing values, so typing a promo code re-runs the total row, the guest stepper and the pay button, even when a written value equals the old one. To narrow it, keep the one-way flow but give the store separate stored properties such as `guests`, `promoCode` and `total`, or split the screen into child stores, so each view depends only on what it reads. Text fields still send actions through `Binding(get:set:)` rather than writing state directly.

code

swift · 31 lines
swift
import SwiftUI

struct CheckoutState: Equatable {
    var guests = 1, promoCode = "", total: Decimal = 0, isPaying = false
}

enum CheckoutAction {
    case setGuests(Int), setPromo(String), payTapped, paymentFinished(succeeded: Bool)
}

@MainActor @Observable
final class CheckoutStore {
    private(set) var state = CheckoutState()   // ONE tracked property for the whole screen
    private let pay: @Sendable (Decimal) async -> Bool
    init(pay: @escaping @Sendable (Decimal) async -> Bool) { self.pay = pay }

    func send(_ action: CheckoutAction) {
        switch action {
        case .setGuests(let count): state.guests = count
        case .setPromo(let code): state.promoCode = code
        case .payTapped:
            state.isPaying = true
            let amount = state.total
            Task {
                let succeeded = await self.pay(amount)
                self.send(.paymentFinished(succeeded: succeeded))
            }
        case .paymentFinished: state.isPaying = false
        }
    }
}

go deeper

for a junior

Know the store's loop: views read state, send actions, and a reducer is the only code that changes state.

for a middle

Explain that Observation tracks the class's stored properties, so one state struct makes every reader depend on every field.

for a senior

Diagnose the redraw storm from the store's shape and fix it with separate stored properties or child stores, keeping actions as the only writes.

for a principal

Decide whether the store's guarantees, one writer and replayable actions, are worth its wiring for a feature, and set its granularity rules up front.

## The store pattern in SwiftUI A **unidirectional store** keeps a screen's state in one object and allows changes only through **actions**: 1. A view reads state from the store and calls `send(_:)` with an action such as `.setPromo("SUMMER")`. 2. A **reducer**, a function from the current state and an action to the next state, applies the change. 3. Work with side effects, such as charging a card, runs as an **effect** that later sends another action, such as `.paymentFinished(succeeded:)`. On iOS 17 and later the store is usually an `@MainActor @Observable final class`, so SwiftUI tracks what views read and every reducer runs on the main actor, where `body` runs. A view that needs a `Binding` gets one from `Binding(get:set:)`, whose setter sends an action, so the reducer stays the only writer. ## Why every view re-runs body Observation does not look inside values. The `@Observable` macro instruments each **stored `var` property of the class**: the getter records an access to that property's key path, and changes notify observers of that key path. When a store declares `private(set) var state: CheckoutState`, the whole screen is one tracked key path, `\CheckoutStore.state`. - A view that reads `store.state.total` has read `state`, so it depends on every field of it. - A reducer that writes `state.promoCode = code` mutates `state` in place, through the macro's `_modify` accessor. - The Swift 6.4 macro source says that accessor deliberately does not compare old and new values, so an in-place mutation always notifies, even when the new value is equal. - Every view whose `body` read any part of `state` is invalidated, so typing one character re-runs the total row, the guest stepper and the pay button. Making `CheckoutState` `Equatable` does not help with in-place mutations: Apple's documented model updates a view when a property it read reports a change, and comparing the struct's fields is no part of that model. ## How to narrow it Keep the one-way data flow; change the **granularity** of what is tracked. | Approach | Effect on updates | Cost | |---|---|---| | one `state` struct | every reader updates on every action | simplest reducer | | separate stored properties on the store | each view updates only for the properties it reads | reducer writes several properties | | child stores per section | a section's views depend only on their child store | more types and wiring | | pass plain values to leaf views | leaf views get values, not the store | parent still re-runs | Separate stored properties are the direct fix: `private(set) var guests`, `promoCode`, `total` and `isPaying` on the store give four key paths, and the reducer can still be a `switch` over actions that assigns them. For a large screen, child stores scoped to a section, such as payment or guest details, keep each reducer small and each dependency narrow. ## Effects and isolation Because the store is `@MainActor`, reducers run on the main actor and state never changes off it. An effect such as payment captures what it needs, runs its `await`, then sends the result back as an action. The `Task` that runs the effect inherits the store's main-actor isolation, so the follow-up `send(_:)` needs no hop of its own, while the awaited payment call runs wherever the payment client's isolation places it. Keep a handle to long-running effects if the screen must cancel them when the person leaves checkout, and send a cancellation action rather than flipping flags from outside the reducer. Keeping the payment client as a `@Sendable` closure or `Sendable` protocol in a `private let` makes it untracked and safe to call across isolation in Swift 6 language mode. ## Checking the fix - Put `Self._printChanges()` in a suspect `body` while debugging to see why it re-ran; the lesson on redraw cost covers the tools. - Type into the promo field and confirm that only the field re-runs. - Make sure no view reads the whole state just to pass it on; pass the store or the specific values instead. ## Where navigation state fits A store often also owns the screen's navigation, for example a typed array bound to `NavigationStack(path:)`. The same rule applies: give the path its own stored property, so pushing a screen does not invalidate every view that reads prices.

  • Why not let the text field bind straight to the store's property with @Bindable?
    That writes the property directly, bypassing the reducer, so the store no longer sees every change as an action, and logging, validation and effects keyed on actions are skipped. With `private(set)` properties it does not even compile from outside the store. `Binding(get:set:)` keeps the one-way flow: reads come from state, writes become `send(.setPromo(…))`.
  • Does replacing the whole state with an equal value avoid the notification?
    In the Swift 6.4 toolchain's `@Observable` macro, a whole-value assignment through the setter skips the notification when an `Equatable` new value equals the old one. In-place mutations through `inout`, which reducers use, never compare. Relying on that difference is fragile; narrowing what each view reads is the reliable fix.

One state struct is like a single group chat for a whole team: any message on any topic notifies everyone in it, even people who follow one thread. Separate stored properties are separate channels, so each person hears only the topics they joined.

  • Observation tracks each field of a struct stored in an observable class separately.
  • Making the state struct Equatable stops redundant redraws from in-place mutations.
  • A unidirectional store means giving up per-property tracking.
  • Text fields should bind directly to store properties with @Bindable.