skip to content

In SwiftUI, why does a @StateObject initialized from a view parameter with StateObject(wrappedValue:) ignore later changes to that parameter, and how do you reset it?

level: seniorimportance: should knowfreq 45%

answer

  1. the initializer runs again, the closure does not
  2. autoclosure, first call only
  3. stable storage by design
  4. identity decides a fresh model

basics

~20 s

StateObject(wrappedValue:) takes an autoclosure that SwiftUI runs only the first time for a view's identity, so later parameter values never build a model. Reset by changing identity with id(_:) or keep the model and update it.

solid answer

~40 s

Assigning `_model = StateObject(wrappedValue: FeedViewModel(category: category))` in `init` stores an `@autoclosure`. When the parent passes a new `category`, SwiftUI re-runs the view's initializer, but it runs the state object's closure only the first time for that view, so the model keeps its first category. That is the stable storage `@StateObject` promises. If a new input should mean a new model, apply `.id(category)` in the parent so the view gets a new identity, accepting that all of its other state resets too. If the screen should stay continuous, keep the model and react to the parameter change by calling a method on it. Keep the property `private` either way.

code

swift · 36 lines
swift
import SwiftUI

@MainActor
final class FeedViewModel: ObservableObject {
    @Published var stories: [String] = []
    let category: String
    init(category: String) { self.category = category }
}

struct FeedView: View {
    @StateObject private var model: FeedViewModel

    init(category: String) {
        // The closure runs only the first time for this view's identity.
        _model = StateObject(wrappedValue: FeedViewModel(category: category))
    }

    var body: some View {
        Text("Showing \(model.category)")
    }
}

struct NewsRoot: View {
    @State private var category = "World"

    var body: some View {
        VStack {
            Picker("Section", selection: $category) {
                Text("World").tag("World")
                Text("Sport").tag("Sport")
            }
            FeedView(category: category)
                .id(category) // new identity, new model
        }
    }
}

go deeper

for a junior

Know that a @StateObject keeps its first model even if the view receives new parameters later.

for a middle

Explain the autoclosure: the view's init runs again, but SwiftUI evaluates the state object's closure only on the first call for that identity.

for a senior

Choose the fix deliberately: id(_:) for a truly new screen with full state reset, or an update method when continuity matters, and say what each costs.

for a principal

Set a team convention for parameterized models so reviewers can spot init-configured state objects and ask which reset behaviour is intended.

## The scenario A news app shows a section picker (World, Sport, Tech) above a feed. The feed view takes the section as a parameter and builds its own view model from it: - `FeedView(category: category)` is created by the parent. - Inside, `init(category:)` assigns `_model = StateObject(wrappedValue: FeedViewModel(category: category))`. The first section loads correctly. Switching to another section changes the label in the parent, but the feed keeps showing the first section's stories. Nothing crashes, and nothing is logged. ## Why the new parameter is ignored `StateObject(wrappedValue:)` takes its argument as an **`@autoclosure`**. Assigning `_model` in the initializer does not create a model; it hands SwiftUI a closure that *would* create one. Apple's documentation for `StateObject` describes exactly this case: 1. When the parent passes a new `category`, SwiftUI runs the view's initializer again with the new value. 2. SwiftUI runs the autoclosure only the **first** time the state object's initializer is called for that view. 3. The later closures, which capture the new category, are discarded without running. So the model keeps its original category. That behaviour is the point of `@StateObject`: it gives **stable storage** even as the view's inputs change. The documentation warns that explicit initialization can produce unexpected behaviour for exactly this reason, and says it works well when the external data does not change for a given instance of the container. ## Fix 1: tie identity to the input If a different input should mean a different model, make it a different view. Apply `id(_:)` in the parent: ```swift FeedView(category: category) .id(category) ``` A new `category` gives the view a new identity; SwiftUI discards the old view and its storage and creates a fresh model from the new parameter. Inside a `ForEach`, each row already carries an implicit identity from its element. When several inputs matter, the documentation suggests combining them into one hashable value, for example with a `Hasher`. The costs are real and worth naming in a review: - **All** state in that view resets, not just the model: `@State`, `@FocusState`, `@GestureState`, and any scroll position kept in that state. - SwiftUI does not automatically animate changes inside the view when its identity changes at the same time. - The old model is released and the new one starts from scratch, so any loading runs again. ## Fix 2: keep the model and update it If the model is expensive, or the screen should keep its scroll position or caches, keep a single owner and **tell** the model about the new input instead. The view reacts to the changed parameter (with `onChange(of:)` or a `task(id:)` keyed on it) and calls a method such as `model.select(category)`. Identity stays, so nothing else resets. | Approach | New model? | Other view state | Good when | |---|---|---|---| | `id(category)` on the view | Yes | Reset | Each input is a different screen | | Keep model, call `select(_:)` | No | Kept | Switching should feel continuous | | Lift the model to the parent | Parent decides | Kept | Several views share the model | ## Rules that keep this safe - Declare the state object **`private`**, even when it is configured through `init`. The documentation says so explicitly, so a memberwise initializer cannot set it and conflict with SwiftUI's storage management. - Keep side effects out of the model's initializer; start loading from `task` so it is tied to the view's appearance. - Do not switch to `@ObservedObject` "so it updates": that recreates the model on every parent redraw, not only when the category changes. - Calling `objectWillChange.send()` does not help; it invalidates the view but never replaces the owned object. ## Recognising it in code review A short checklist for a pull request that adds a configurable state object: 1. Does the `init` parameter that feeds the model ever change while the view is on screen? 2. If it does, is there an `id(_:)` on the call site, or does the model expose a method that the view calls when the parameter changes? 3. Is the property still `private`, and is loading started from `task` rather than from the model's initializer? The tell is an `init` that writes to `_model = StateObject(wrappedValue: ...)` using a parameter that can change while the view is on screen. Ask the author which behaviour they want when that parameter changes, then choose identity or an update method deliberately. A similar rule holds for an `@Observable` model owned with `@State` and configured in `init`: SwiftUI keeps the first stored value. That case belongs with view-owned values.

  • Why does the documentation insist the state object stay private even when it is set in init?
    A non-private property can be set through the view's memberwise initializer, which conflicts with the storage SwiftUI manages for the state object and produces unexpected results. Keeping it `private` forces configuration through your own `init` and the autoclosure.
  • The model depends on two inputs, category and region. How do you reset it when either changes?
    Give the view one identity built from both, for example a small `Hashable` struct of the two values, or a hash combined with `Hasher`, and pass it to `id(_:)`. Either input changing then changes identity and creates a new model, with the same reset of all other view state.

  • Expects the model to rebuild whenever the init parameter changes
  • Switches to @ObservedObject so the model follows the parameter
  • Calls objectWillChange.send() hoping it rebuilds the model
  • Drops private so the parent can assign the state object directly
  • Thinks id(_:) resets only the @StateObject and keeps other @State