Pocket How
SwiftUI

SwiftUI @Observable state management: @State, @Bindable and @Environment

iOS 17+, iPadOS 17+. Intermediate. By Cihat Salik, .

Short answer

Mark model classes with @Observable, own them with @State in the view that creates them, pass them down as plain properties, use @Bindable when a child needs bindings, and share app-wide models with .environment(model) and @Environment(Model.self). Keep initializers cheap, because before Xcode 27 a @State initial value runs on every parent update.

The problem

SwiftUI gives you a handful of tools for state, and most bugs come from picking the wrong one for a given piece of data. A model recreated on every parent update, a list that redraws every row when one item changes, a sheet that edits a copy instead of the original: each of these traces back to a decision about where a value lives and who owns it. Since iOS 17 the Observation framework replaces most of the ObservableObject machinery, and the rules got simpler, but a few of them changed in ways that are easy to miss when you migrate.

The four tools and what each one means

Observation starts with the @Observable macro (iOS 17+). It expands a class so every stored property reports reads and writes. SwiftUI records which properties a view’s body reads and invalidates that view only when one of those properties changes. Apple’s migration guide spells out the difference: with ObservableObject, a view updates when any @Published property changes, even one it never reads.

Then you have four ways to hold a model in a view:

  • @State: this view creates and owns the instance. SwiftUI keeps it alive for the lifetime of the view’s identity.
  • A plain let or var: the view received the instance from a parent. Observation still works, because tracking happens on property access, not through a wrapper.
  • @Bindable: the view received the instance and needs $model.property bindings for controls like TextField or Toggle.
  • @Environment(Model.self): the instance was placed into the environment higher up with .environment(model).

Donny Wals sums up the ownership rule in @Observable in SwiftUI explained: only the view that creates the object applies @State. Every view below it takes a plain property, and reaches for @Bindable only when it needs bindings. If you hold a model in @State, you already get bindings through $model, so @Bindable is redundant there.

A worked example

Here is a small library app with one app-wide store, a list, a detail editor and local UI state. It compiles in the Swift 6 language mode with strict concurrency.

import SwiftUI

struct Book: Identifiable, Hashable, Sendable {
    let id: UUID
    var title: String
    var isFavorite = false
}

@MainActor
@Observable
final class LibraryStore {
    var books: [Book] = []
    var searchText = ""

    var visibleBooks: [Book] {
        guard !searchText.isEmpty else { return books }
        return books.filter { $0.title.localizedStandardContains(searchText) }
    }

    func load() async {
        books = [
            Book(id: UUID(), title: "The Left Hand of Darkness"),
            Book(id: UUID(), title: "Piranesi")
        ]
    }

    func toggleFavorite(_ id: Book.ID) {
        guard let index = books.firstIndex(where: { $0.id == id }) else { return }
        books[index].isFavorite.toggle()
    }
}

@main
struct LibraryApp: App {
    @State private var store = LibraryStore()

    var body: some Scene {
        WindowGroup {
            LibraryView()
                .environment(store)
                .task { await store.load() }
        }
    }
}

struct LibraryView: View {
    @Environment(LibraryStore.self) private var store

    var body: some View {
        @Bindable var store = store
        NavigationStack {
            List(store.visibleBooks) { book in
                NavigationLink(book.title, value: book.id)
            }
            .searchable(text: $store.searchText)
            .navigationDestination(for: Book.ID.self) { id in
                BookDetail(store: store, bookID: id)
            }
            .navigationTitle("Library")
        }
    }
}

struct BookDetail: View {
    let store: LibraryStore
    let bookID: Book.ID
    @State private var isConfirmingDelete = false

    var body: some View {
        if let book = store.books.first(where: { $0.id == bookID }) {
            Form {
                Text(book.title)
                Button(book.isFavorite ? "Remove favorite" : "Add favorite") {
                    store.toggleFavorite(bookID)
                }
                Button("Delete", role: .destructive) {
                    isConfirmingDelete = true
                }
            }
            .confirmationDialog("Delete book?", isPresented: $isConfirmingDelete) {
                Button("Delete", role: .destructive) {}
            }
        }
    }
}

A few things to notice.

The store lives in @State on the App. Jesse Squires recommends this placement for app-level state in his post on the macro: the App struct is created once, so its initializers never repeat.

LibraryView reads the store from the environment, then declares @Bindable var store = store inside body to get $store.searchText. Environment values can’t produce bindings on their own. A local @Bindable is the documented way around that, and Donny Wals shows the same pattern.

BookDetail takes the store as a plain let. It reads store.books, so it updates when the array changes. It does not need @Bindable because it mutates through a method.

The confirmation flag is a Bool in @State. Value types that only one view cares about stay in that view. Moving them into the store would make every reader of the store a candidate for extra updates and would leak UI details into your model.

Where state should live

Ask two questions about each value: who needs to read it, and who needs to change it.

The value is read by And changed by Put it in
One view That view @State with a value type
One view and its children Children via controls @State in the parent, @Binding or @Bindable in children
Many unrelated screens Many screens An @Observable class in the environment
A screen and survives navigation The screen An @Observable class owned by a view that outlives the screen
The system across launches User settings @AppStorage or your own persistence

Keep @State private. A @State property is storage owned by SwiftUI, and a parent that sets it through the initializer only provides the first value. Later changes from the parent are ignored, which looks like a bug when it is the documented behavior.

Migrating from ObservableObject

Apple’s migration guide lays out the mapping, and you can do it one type at a time. @StateObject and @EnvironmentObject accept @Observable types, so an app can mix both systems during the transition.

Before After
class Model: ObservableObject @Observable class Model
@Published var value var value
A property you don’t want tracked @ObservationIgnored var value
@StateObject private var model = Model() @State private var model = Model()
@ObservedObject var model: Model var model: Model, or @Bindable var model: Model for bindings
.environmentObject(model) .environment(model)
@EnvironmentObject var model: Model @Environment(Model.self) private var model

Antoine van der Lee suggests checking the before and after behavior with view debugging when you migrate, in his write-up on the performance difference. His example shows a view that redrew on an unrelated property change under ObservableObject and stopped doing so after the switch. That is the main payoff, and it is also the main behavior change: code that relied on a view refreshing “for free” when any property changed may now stop refreshing.

Combine pipelines on @Published properties need a replacement. withObservationTracking reports only the next change, so you re-register after each one, a limitation Donny Wals points out. On iOS 26 and later, the Observations async sequence tracks changes for you:

import Observation

@MainActor
func logSearches(in store: LibraryStore) async {
    if #available(iOS 26, *) {
        let searches = Observations { store.searchText }
        for await text in searches {
            print("Search changed to", text)
        }
    }
}

The bugs you will meet

The model initializer runs more than once

This is the one that surprises people who migrated. @StateObject takes its initial value as an autoclosure, so the object is created once. Before Xcode 27, @State took the value directly. Every time a parent re-evaluated and recreated a child view struct, the expression Model() ran again, and SwiftUI then threw the new instance away and kept the original. Jesse Squires describes how those discarded instances can still register for notifications or write to UserDefaults, leading to last-write-wins bugs.

Natalia Panferova explains in her Nil Coalescing article that @State becomes a macro in Xcode 27 and evaluates its initial value lazily, once, when SwiftUI sets up storage. The change back-deploys to iOS 17 as long as you compile with Xcode 27. She also notes that assigning to _model = State(initialValue:) inside a view’s init still runs on every recreation, so that pattern stays off the table.

The practical rule holds for every toolchain: keep init free of side effects and expensive work. Load data in .task, and when the model depends on a value from the parent, key the load to it:

struct AuthorScreen: View {
    let authorID: UUID
    @State private var model = AuthorModel()

    var body: some View {
        Text(model.name)
            .task(id: authorID) { await model.load(authorID) }
    }
}

@MainActor
@Observable
final class AuthorModel {
    var name = ""
    func load(_ id: UUID) async {
        name = "Author \(id.uuidString.prefix(4))"
    }
}

Apple’s Demystify SwiftUI performance session makes the same point from the other side: a model whose initializer fetches synchronously slows every update that touches it.

A child owns state it should have received

If a child view declares @State private var model = DetailModel() but the parent already has the data, the child gets its own copy and the two drift apart. When the parent swaps the child’s identity, for example by changing .id(_:) or switching an if branch, the child’s state resets. Pass the instance down instead. Ownership goes to the highest view that needs the value, and no higher.

One read makes every row depend on the whole array

Observation tracks property access, and a computed property counts as reading everything it touches. In the WWDC25 Instruments session, each list row called a helper that searched the full favorites array. Every row therefore depended on the array, and adding one favorite re-ran every visible row’s body. The fix gave each item its own observable object so a row reads only its own flag:

@MainActor
@Observable
final class FavoriteState {
    var isFavorite = false
}

@MainActor
@Observable
final class FavoritesStore {
    @ObservationIgnored private var states: [UUID: FavoriteState] = [:]

    func state(for id: UUID) -> FavoriteState {
        if let existing = states[id] { return existing }
        let created = FavoriteState()
        states[id] = created
        return created
    }
}

The dictionary is @ObservationIgnored, so creating an entry does not invalidate anyone. A row that reads store.state(for: id).isFavorite now depends on one Boolean.

The environment is missing a value

@Environment(Model.self) crashes at runtime when no ancestor injected that type, exactly like @EnvironmentObject did. Previews and sheets are the usual culprits. Inject the model at the root of every preview, and remember that a model placed on one window’s view tree is not visible to another WindowGroup scene.

Frequent values in the environment

Apple’s performance article and the WWDC25 session both warn that every view reading the environment gets checked when any environment value changes. Don’t push timers, scroll offsets or geometry into the environment. Pass them to the few views that need them.

Structs and actors

The macro applies to classes only. A struct with value semantics already works with @State and @Binding. Actors can’t be @Observable either; SwiftUI reads properties synchronously on the main actor, so keep observable models @MainActor and run background work in separate actors or tasks that hand results back.

Checklist

  • Model types are @MainActor @Observable final class.
  • Exactly one view owns each model with @State. Everyone else takes a plain property.
  • @Bindable appears only where a control needs a binding to a model you received.
  • App-wide models are created in the App struct and shared with .environment(_:).
  • Initializers do no I/O, register no observers and start no tasks. Loading lives in .task or .task(id:).
  • Local UI flags are private @State values, not model properties.
  • Caches, task handles and lookup tables are @ObservationIgnored.
  • Rows read the narrowest property they can. Verify with the SwiftUI instrument in Instruments, which shows the cause of each update in its cause-and-effect graph.

Sources and further reading

Read next