Initialize StateObject with a parameter in SwiftUI
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
@StateObject is the right property wrapper when a SwiftUI view owns the lifecycle of an observable reference type. Initializing it with runtime data is common, but the syntax is easy to get wrong if you try to assign directly in the property declaration. The correct pattern is to initialize the backing storage in the view initializer.
Why @StateObject Needs Special Initialization
@StateObject is created once per view identity, not on every body recomputation. That behavior protects your model from being recreated during state updates.
Because of that lifecycle guarantee, SwiftUI requires initialization through the underscored storage property in init, using StateObject(wrappedValue:).
Incorrect pattern:
Here, userId is not available when the property is initialized.
Correct pattern:
Parent to Child Data Flow Patterns
When the parent creates and owns the model, pass it as @ObservedObject instead of @StateObject.
Ownership rule:
- creator and lifecycle owner uses
@StateObject - consumer uses
@ObservedObject
Following this rule prevents accidental double initialization and confusing state resets.
Handling Parameter Changes Safely
A common misunderstanding is expecting @StateObject to recreate when input parameters change. It does not, unless the view identity changes.
If you need recreation for a different key, tie identity explicitly:
Using .id tells SwiftUI this is a new view identity, so @StateObject is rebuilt.
If recreation is not desired, update the existing model instead by exposing an update method and calling it on change.
That pattern avoids tearing down existing async tasks unless you choose to.
Async Loading Example with Cancellation
Many view models start async work. Keep cancellation inside the model to avoid stale updates.
This keeps the view simple and makes model behavior testable.
Testing Guidance
For unit tests, instantiate the view model directly and verify published state transitions. For UI tests, vary navigation paths and parameter changes to ensure model ownership remains stable.
A useful check is confirming the model is not re-created on trivial body updates. Logging object identity during development can reveal unintended resets.
Common Pitfalls
A frequent pitfall is using @ObservedObject when the view should own creation. The model may be recreated externally and produce inconsistent state.
Another issue is putting expensive network calls in the view initializer. Keep side effects in methods triggered by .task or .onAppear so lifecycle is explicit.
Developers also forget that changing a constructor argument does not automatically recreate @StateObject. Use .id only when full recreation is intentional.
Finally, avoid storing parent-owned dependencies inside child-owned models without a clear ownership boundary.
Summary
- Initialize
@StateObjectwith parameters via_property = StateObject(wrappedValue:)ininit. - Use
@StateObjectfor ownership and@ObservedObjectfor consumption. - Parameter changes do not recreate state objects unless view identity changes.
- Prefer explicit update methods or
.task(id:)for changing inputs. - Keep async cancellation and side-effect management inside the view model.
Related reading
- Initializer is inaccessable due to 'internal' protection level
- Initializer is inaccessable due to 'internal' protection level
- Input text dialog Android
- input typenumber/ is not showing a number keypad on iOS
- Install an apk file from command prompt?
- Install Android App Bundle on device
- Install Application programmatically on Android
- INSTALL_FAILED_NO_MATCHING_ABIS when install apk
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.