State Management

Article · 2:00

@State, @Binding, @Observable and @Environment - deciding where a piece of data lives.

Views are structs, thrown away and rebuilt constantly, so a plain var inside one cannot hold anything across a redraw. The property wrappers exist to park state somewhere that outlives the struct, and choosing between them is really one question: who owns this value.

@State is for a value a view owns privately - a toggle, a text field's contents, whether a sheet is showing. Mark it private, always. @Binding is for a value a view uses but does not own: the parent holds the @State and passes $value, and the child can read and write the parent's copy. The $ is how you get a binding from state.

For a model shared across several screens, make a class and mark it @Observable. SwiftUI then tracks which of its properties each view actually reads, and redraws only the views that read the one that changed. This is the modern replacement for ObservableObject and @Published, and it is both less code and less work at runtime.

@Environment reaches for values the system or an ancestor put in scope - the colour scheme, the dismiss action, a model object injected high up the tree. Use it to avoid threading the same object through five initialisers.

The rule that keeps all of this straight: one source of truth. Every piece of data is owned in exactly one place and everything else reads it or binds to it.

import SwiftUI
import Observation

// A model shared between screens. @Observable tracks property reads.
@Observable
final class BasketModel {
    var items: [String] = []
    var isCheckingOut = false
    var count: Int { items.count }
}

struct BasketScreen: View {
    // This view OWNS the model, so it creates and holds it.
    @State private var basket = BasketModel()
    // This view owns a private piece of interface state.
    @State private var draft = ""

    var body: some View {
        VStack(spacing: 16) {
            // $draft makes a Binding from the State.
            TextField("Add an item", text: $draft)
                .textFieldStyle(.roundedBorder)

            Button("Add") {
                guard !draft.isEmpty else { return }
                basket.items.append(draft)
                draft = ""
            }

            // The child does not own the model, it is handed it.
            BasketCount(basket: basket)
        }
        .padding()
        .environment(basket)      // and anything deeper can reach it
    }
}

struct BasketCount: View {
    let basket: BasketModel
    var body: some View {
        // Only this view redraws when count changes - not the whole screen.
        Text("\(basket.count) item(s)").foregroundStyle(.secondary)
    }
}

#Preview { BasketScreen() }