State Management in SwiftUI

Every SwiftUI bug about data eventually turns out to be a bug about ownership. A view is a value that the framework throws away and rebuilds, so a value cannot simply live inside one and expect to survive. SwiftUI solves this by moving state into storage outside the view tree and by giving you a small vocabulary of property wrappers that say, precisely, who owns a piece of state, who may read it, and who may write it. This chapter is about that vocabulary. It starts with the two wrappers everyone meets first, moves to the modern Observation framework that replaced half of the old API, explains what the environment is for, and then deals with the parts of the topic that are less about syntax than about judgement: how to stop the state from spreading across your whole app, how to run asynchronous work safely, and how to pass values through a navigation stack without losing them.

The mental model to carry through everything below is this: a view describes, state decides, and the framework connects the two. If you find yourself unsure which wrapper to reach for, ask the three questions in the next section and the answer usually falls out.

1. Three questions about any piece of state

Before you write a single property, answer three questions.

Who owns it? Someone has to be responsible for creating it and for destroying it. In SwiftUI that is either the view itself or an ancestor further up the tree, or an object that exists outside the view tree entirely.

Who may read it? Anyone can be handed a copy of a value, but reading a live value requires a connection, because the reader must be told when the value changes.

Who may write it? This is the question that separates @State from @Binding, and it is the one people most often get wrong.

Every wrapper in the table below is an answer to those three questions. Choosing the wrong one produces the two classic symptoms: a value that changes but the screen does not update, and a value that updates the screen but resets to its initial value at the wrong moment.

2. @State: a value the view owns

@State is for value types that the view owns outright: a String, an Int, a Bool, an array, a struct.

struct Counter: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 12) {
            Text("Tapped \(count) times")
                .font(.title2)

            HStack {
                Button("Decrement") { count -= 1 }
                Button("Increment") { count += 1 }
            }
        }
    }
}

Three properties of @State explain nearly everything about it.

The view is the owner. The declaration is the only place the value is created. Nothing else can write to it.

The storage lives outside the view. @State is not a stored property in the usual sense. It is a property wrapper whose wrapped value is a reference to storage SwiftUI keeps outside the view struct, keyed by the view’s identity. That is why mutating count inside the button action is legal even though body is a non-mutating getter.

The storage survives re-creation, but not identity changes. When the framework rebuilds Counter because count changed, the new value of the @State property is the old one, because the storage is keyed by identity. But if the view’s identity changes, the storage is thrown away and the initialiser runs again. Identity changes when you change the type of the view in a conditional branch, or when you attach a different .id() to it.

@State private var draft: Draft = Draft()

// Changing the identifier resets the storage and the draft is lost.
TextField("Title", text: $draft.title)
    .id(editingID)

@State should be private unless another view genuinely needs to write it. The exception is a @Binding, which is the next section.

3. @Binding: a two-way connection

A child view often needs to change something the parent owns. It should not get a copy, because a copy cannot be written back. It should get a binding: a two-way connection to the parent’s storage.

struct TextFieldRow: View {
    let title: String
    @Binding var text: String

    var body: some View {
        HStack {
            Text(title)
            Spacer()
            TextField("Value", text: $text)
                .multilineTextAlignment(.trailing)
        }
    }
}

The parent creates the binding with the $ projection, which is available on any property that has a projected value.

struct SettingsForm: View {
    @State private var username = ""
    @State private var isEnabled = true

    var body: some View {
        Form {
            TextFieldRow(title: "Username", text: $username)
            Toggle("Enabled", isOn: $isEnabled)
        }
    }
}

$username is a Binding<String>. Reading text inside the child reads the parent’s storage, and writing to it writes back to the parent’s storage. That is why a TextField needs a binding rather than a plain String: the field is a two-way editor, and a plain value can only be read.

Inside the child, $text is the binding itself, and $text.wrappedValue is the current value. Passing $text to a further child creates another binding to the same storage, so the chain does not break.

The rule for bindings is simple: you can pass a binding down, never up. If a child needs to change something that only an ancestor owns, the ancestor has to hand down a binding, or the state has to move somewhere both can reach.

4. @Observable: the modern way to model shared data

A single view with a @State property is easy. The moment two or three views need the same value, you need a shared model, and this is where the API has changed most.

The current approach, available from iOS 17, is the @Observable macro.

import SwiftUI
import Observation

@Observable
final class ShoppingCart {
    var items: [String] = []
    var discount: Double = 0

    var total: Double {
        items.reduce(0) { $0 + 1 }
    }

    func add(_ item: String) {
        items.append(item)
    }
}

The macro rewrites the stored properties into tracked properties and synthesises the machinery that Observation needs. The important consequence is what you do not write: there is no @Published, no ObservableObject conformance, no objectWillChange, and no Combine import.

Using it from a view is also simpler than the old API.

struct CartView: View {
    @State private var cart = ShoppingCart()

    var body: some View {
        VStack {
            Text("Total: \(cart.total)")

            ForEach(cart.items, id: \.self) { item in
                Text(item)
            }

            Button("Add item") {
                cart.add("Coffee")
            }
        }
    }
}

Three rules make this work, and each one replaces a rule from the old API.

The owner uses @State. @State private var cart = ShoppingCart() creates the model and keeps it alive for as long as the view’s identity is stable. This is the direct replacement for @StateObject.

Receivers take a plain property. There is no wrapper.

struct CartRow: View {
    let cart: ShoppingCart

    var body: some View {
        Text("\(cart.items.count) items")
    }
}

The child does not need to know how the model is owned, and does not need a wrapper to be told when it changed. Reading cart.items during body registers a dependency on that property, and the view is invalidated when it changes. Reading a different property does not register a dependency on the first one, so the tracking is fine-grained: changing discount does not redraw a view that only read items.

Injection uses the environment or a parameter. To put the model into the environment, call .environment(cart) on an ancestor and read it with @Environment(ShoppingCart.self). To pass it down, pass it as a normal property.

The one thing to keep in mind is that @Observable models are reference types. A class instance stored in @State is owned by the view, but the object itself is shared with whoever else holds a reference to it, and mutating it does not copy.

5. @Environment and @EnvironmentObject

The environment is a context that any ancestor can fill and any descendant can read. It exists to solve a specific problem: a deeply nested view that needs a value which has nothing to do with the intermediate views in between.

System-provided values, such as the colour scheme or the dismiss action, come from the framework.

struct DetailView: View {
    @Environment(\.colorScheme) private var colorScheme
    @Environment(\.dismiss) private var dismiss
    @Environment(\.openURL) private var openURL

    var body: some View {
        VStack {
            Text("Rendering in \(colorScheme == .dark ? "dark" : "light")")

            Button("Close") { dismiss() }
        }
    }
}

Your own values work the same way, but you have to declare the key.

private struct ThemeKey: EnvironmentKey {
    static let defaultValue = Theme.system
}

extension EnvironmentValues {
    var theme: Theme {
        get { self[ThemeKey.self] }
        set { self[ThemeKey.self] = newValue }
    }
}

Inject it with .environment(\.theme, .dark) and read it with @Environment(\.theme) private var theme.

@EnvironmentObject is the older, object-flavoured version of the same idea. It reads an object that an ancestor injected with .environmentObject(model).

struct SettingsView: View {
    @EnvironmentObject private var model: AppModel

    var body: some View {
        Toggle("Notifications", isOn: $model.notificationsEnabled)
    }
}

The problem with @EnvironmentObject is that it is a dynamic property with a runtime failure mode: if nothing above injected the object, the view crashes with a fatal error the first time it reads the property. With @Observable models the modern equivalent is @Environment(AppModel.self), which is also a dynamic property with the same requirement, or simply passing the model down as a parameter.

SituationOld APICurrent API
Own an observable model@StateObject var model = Model()@State private var model = Model()
Receive one from a parent@ObservedObject var model: Modellet model: Model
Receive one from the environment@EnvironmentObject var model: Model@Environment(Model.self) var model

6. The older framework, and when you still meet it

ObservableObject and @Published are not deprecated and are still everywhere in existing code. They work by a different mechanism: the object publishes a change signal through Combine, and SwiftUI re-reads the body.

final class AppModel: ObservableObject {
    @Published var username = ""
    @Published var isEnabled = true
}

The wrappers then describe ownership.

@StateObject creates the object and owns it. The initialiser expression runs exactly once, not on every re-creation of the view, which is why the object is created as a declared property rather than inside body.

struct SettingsView: View {
    @StateObject private var model = AppModel()

    var body: some View {
        TextField("Username", text: $model.username)
    }
}

@ObservedObject observes an object that somebody else created and passed in.

struct SettingsRow: View {
    @ObservedObject var model: AppModel

    var body: some View {
        TextField("Username", text: $model.username)
    }
}

@EnvironmentObject observes an object that an ancestor injected.

@main
struct MyApp: App {
    @StateObject private var model = AppModel()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(model)
        }
    }
}

The old rules map cleanly onto the new ones, and the migration is mechanical: drop ObservableObject and @Published, add the @Observable macro, change @StateObject to @State, change @ObservedObject to a plain let, and change @EnvironmentObject to @Environment(Model.self) with .environment(model) at the injection point.

7. Choosing the right wrapper

What you haveWhat to writeWhy
A value type the view owns@State private var x = ...The view creates and owns it
A value type owned by an ancestor@Binding var x: TypeTwo-way connection to the parent
A constant inputlet x: TypeIt never changes, so it is not state
An observable model the view owns@State private var model = Model()Modern replacement for @StateObject
An observable model from a parentlet model: ModelReading it registers the dependency
An observable model from the environment@Environment(Model.self) var modelModern replacement for @EnvironmentObject
A system or custom environment value@Environment(\.key) var valueFramework-provided context

The most common mistake in the table above is using @State for a model that other views share, and then wondering why the other views do not update. @State on a reference type does not make the object observable; it only makes the reference state. Wrap the class in @Observable and the sharing works.

8. Lifetime, identity, and reset

State has a lifetime that is not the same as the lifetime of the view struct.

The @State storage is keyed by the identity of the view. As long as the identity is stable, the storage survives every rebuild of the view. When the identity changes, the storage is discarded and the initialiser runs again, which is the moment a form resets to blank and a scroll position jumps to the top.

Identity changes in three common situations.

A different type in the same position. In a if/else where the two branches produce different types, SwiftUI treats them as different views.

if isEditing {
    EditRow(text: $text)     // a different type from DisplayRow
} else {
    DisplayRow(text: text)
}

Wrapping both branches in a Group with a stable structure, or using AnyLayout, avoids the reset.

An explicit .id(). .id(someValue) is a deliberate identity change. Whenever that value changes, the subtree is rebuilt from scratch and all of its @State is lost. It is the right tool for “these two items are genuinely different entities” and the wrong tool for “I want to force a refresh”.

A change of position in a conditional list. The framework uses the identity of the data item, given by id in a ForEach, to decide whether a row is the same row. Rows without a stable id can swap state when the list is reordered.

ForEach(items, id: \.id) { item in
    NavigationLink(value: item) {
        Text(item.title)
    }
}

9. Keeping state from exploding

A codebase degrades into a state-management problem in a predictable way: a new feature needs a value from somewhere far away, so the value is copied into a nearer view, then copied again, until the copies disagree. The cure is not a cleverer wrapper; it is a smaller amount of state.

Store the source, derive the rest. If a value can be computed from other state, compute it instead of storing it.

// Worse: two copies of the same fact.
@State private var items: [Item] = []
@State private var itemCount = 0

// Better: one fact, one derived value.
@State private var items: [Item] = []

var itemCount: Int { items.count }

Model mutually exclusive states as an enum. A set of booleans such as isLoading, isEmpty and hasError admits impossible combinations. An enum makes each state exactly one value.

enum LoadState {
    case idle
    case loading
    case loaded([Item])
    case failed(Error)
}

@State private var state: LoadState = .idle

Pass inputs, not state. A child that receives a value it cannot change should receive it as a let, and a child that needs to change it should receive a @Binding. If a child needs to change a value that it was not given, that value is in the wrong place.

Keep models at the level where they are used. An @Observable model should live at the level of the feature that owns it, not at the top of the app. Putting one global model in the environment and reading it from every view is the shape that produces the most confusing code in a SwiftUI codebase.

10. Asynchronous work with Task

SwiftUI provides a structured way to run asynchronous work that is tied to the lifetime of a view: the .task modifier.

struct ProfileView: View {
    @State private var profile: Profile?
    @State private var isLoading = true

    var body: some View {
        Group {
            if let profile {
                ProfileDetail(profile: profile)
            } else if isLoading {
                ProgressView()
            } else {
                ContentUnavailableView("No profile", systemImage: "person.slash")
            }
        }
        .task {
            isLoading = true
            profile = try? await ProfileService.shared.load(id: userID)
            isLoading = false
        }
    }
}

The .task modifier starts the work when the view appears and cancels it automatically when the view disappears. The cancellation propagates into any async function you call, provided those functions check for cancellation. That automatic cancellation is the whole reason to prefer .task over firing a Task inside .onAppear.

func load(id: String) async throws -> Profile {
    try Task.checkCancellation()          // fail fast if the view went away
    let (data, _) = try await URLSession.shared.data(from: url)
    try Task.checkCancellation()
    return try JSONDecoder().decode(Profile.self, from: data)
}

If you must start work from .onAppear, keep the task in @State and cancel it yourself.

@State private var loadTask: Task<Void, Never>?

.onAppear {
    loadTask = Task {
        await refresh()
    }
}

.onDisappear {
    loadTask?.cancel()
}

Two more rules matter in practice. SwiftUI views are not @MainActor isolated by default, but in practice everything they touch is main-actor bound, so call await MainActor.run when a background task needs to update state directly. And never start an unbounded Task from a view body, because the body is evaluated many times.

11. Navigation and passing values

NavigationStack holds a path of destinations. The path is state, so it can be bound, stored, restored, and set from a deep link.

struct NavigationRoot: View {
    @State private var path: [Route] = []

    var body: some View {
        NavigationStack(path: $path) {
            List(items) { item in
                NavigationLink(value: Route.detail(item)) {
                    Text(item.title)
                }
            }
            .navigationDestination(for: Route.self) { route in
                switch route {
                case .detail(let item):
                    DetailView(item: item)
                case .settings:
                    SettingsView()
                }
            }
        }
    }
}

Values are pushed with NavigationLink(value:) and matched by navigationDestination(for:). The value must be Hashable, which is why Route is an enum rather than a class.

The same path can be driven from outside, which is how a deep link works.

.onOpenURL { url in
    guard url.scheme == "myapp" else { return }

    switch url.host {
    case "item":
        if let id = url.pathComponents.dropFirst().first,
           let item = items.first(where: { $0.id == id }) {
            path = [Route.detail(item)]
        }
    case "settings":
        path = [Route.settings]
    default:
        break
    }
}

Assigning to the path replaces it, which is what a deep link should do: the user lands on a specific screen, not on a screen stacked on top of an arbitrary history.

12. Common mistakes

MistakeWhat happensCorrection
@State on an observable classOther views never updateAdd the @Observable macro, or use ObservableObject with @Published
Passing a plain value where a binding is neededThe field cannot be editedPass $value and declare @Binding in the child
Creating an observed object inside bodyA new object on every evaluationDeclare it with @StateObject or @State at the property level
Forgetting to inject an environment objectA runtime crash on first readInject with .environmentObject or .environment
Copying derived values into stateThe copies drift apartCompute them instead
Firing a Task from bodyWork starts again on every rebuildUse the .task modifier
Changing .id() to force a refreshAll child state is discardedFix the underlying identity problem
Reading a @State value in a detached taskA data race and a stale readHop back to the main actor before touching state

13. Exercise

Build a LibraryView with three screens: a list of books, a detail screen for one book, and a settings screen. Use an @Observable model called LibraryModel that owns the books and a isSortedByTitle flag, and create it in the root view with @State. Give the model a computed property sortedBooks that returns the books in the right order, and do not store the sorted array. Present the detail screen with NavigationStack and a NavigationLink(value:), using a Hashable enum for the route. Add a settings screen reachable from a toolbar button, and put the model into the environment with .environment(model) so that the settings screen can read it with @Environment(LibraryModel.self) and toggle the sort flag without any binding. Finally, add a .task that loads the books asynchronously and must cancel cleanly if the user navigates away before it finishes.

Check the behaviour by toggling the sort order and confirming the list order changes while the detail screen keeps showing the book you tapped, and by navigating away during the load to confirm the task cancels without a crash.

swiftui state managementobservableenvironmentnavigation

Approach:

The exercise is designed so that each screen forces one ownership decision, and the decisions have to be made in a particular order. The root view owns the model, so it creates it with @State and injects it into the environment. Everything below the root therefore reads the same instance without any of them needing to know who created it. The detail screen receives a value through the navigation path, not a reference to the model, because a route has to be Hashable and because a route describes where you are, not what you own. The sort order is derived rather than stored, so there is exactly one list of books in the program and no chance of the two disagreeing.

Steps:

  1. Declare the model as an @Observable final class with a stored books array and a stored isSortedByTitle flag, plus a sortedBooks computed property that returns either books or books.sorted by title. Do not add a stored sorted array.
  2. Create the model in the root view with @State private var model = LibraryModel(), so the model is created once and owned by the root view for as long as its identity is stable.
  3. Define a Hashable route enum with a detail case carrying the book and a settings case, and give the book a stable id so it can be used in a ForEach and in a NavigationLink(value:).
  4. Hold the navigation path in @State private var path: [Route] = [], present a NavigationStack(path: $path), push the detail route with NavigationLink(value: Route.detail(book)), and handle the routes in a single navigationDestination(for: Route.self) with a switch.
  5. Inject the model at the root with .environment(model) so that any descendant can read it with @Environment(LibraryModel.self) private var model.
  6. In the settings screen, toggle model.isSortedByTitle directly on the environment model. Because the model is @Observable and the toggle reads the property during body, the list view is invalidated automatically when the flag changes, with no binding and no manual notification.
  7. Add .task { await model.loadBooks() } to the list, and inside loadBooks call try Task.checkCancellation() before and after the network call so that the work stops promptly when the view disappears.

Answer:

import SwiftUI
import Observation

@Observable
final class LibraryModel {
    var books: [Book] = []
    var isSortedByTitle = false
    var isLoading = false

    var sortedBooks: [Book] {
        isSortedByTitle ? books.sorted { $0.title < $1.title } : books
    }

    func loadBooks() async {
        isLoading = true
        defer { isLoading = false }

        do {
            try Task.checkCancellation()
            books = try await BookService.shared.fetchBooks()
            try Task.checkCancellation()
        } catch is CancellationError {
            // The view went away; nothing to report.
        } catch {
            books = []
        }
    }
}

struct Book: Identifiable, Hashable {
    let id: String
    let title: String
    let author: String
}

enum Route: Hashable {
    case detail(Book)
    case settings
}

struct LibraryView: View {
    @State private var model = LibraryModel()
    @State private var path: [Route] = []

    var body: some View {
        NavigationStack(path: $path) {
            List(model.sortedBooks) { book in
                NavigationLink(value: Route.detail(book)) {
                    VStack(alignment: .leading) {
                        Text(book.title)
                        Text(book.author)
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                }
            }
            .overlay {
                if model.isLoading {
                    ProgressView()
                }
            }
            .navigationTitle("Library")
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button {
                        path.append(.settings)
                    } label: {
                        Image(systemName: "gearshape")
                    }
                }
            }
            .navigationDestination(for: Route.self) { route in
                switch route {
                case .detail(let book):
                    BookDetailView(book: book)
                case .settings:
                    LibrarySettingsView()
                }
            }
        }
        .environment(model)
        .task {
            await model.loadBooks()
        }
    }
}

struct BookDetailView: View {
    let book: Book

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(book.title).font(.title)
            Text(book.author).foregroundStyle(.secondary)
            Spacer()
        }
        .padding()
        .navigationTitle(book.title)
    }
}

struct LibrarySettingsView: View {
    @Environment(LibraryModel.self) private var model

    var body: some View {
        Form {
            Section("Sorting") {
                Toggle("Sort by title", isOn: $model.isSortedByTitle)
            }
        }
        .navigationTitle("Settings")
    }
}

Note the Toggle in the settings screen. Even though model was obtained from the environment rather than declared with @State, $model.isSortedByTitle works, because the @Observable macro gives every tracked property a projected value that produces a binding. That binding reads and writes the same instance the list is reading from, so the list updates without any explicit refresh.

The behaviours worth verifying are that the list reorders as soon as the toggle is flipped, that the detail screen still shows the book that was tapped even after the list is reordered, and that navigating away during the load cancels the task without leaving the loading indicator stuck on.

Found an issue with this content?

Tell us what could be improved.