Key difference between StateObject vs ObservedObject in SwiftUI?

When would you use @StateObject vs @ObservedObject in SwiftUI?
Both @StateObject and @ObservedObject are used to monitor an observable object for changes and automatically update the view when those changes occur.
But the key difference is about ownership and lifecycle management.

📕 @StateObject
Use when you create the object inside the view
SwiftUI takes ownership and ensures it persists across re-renders
Introduced in SwiftUI 2.0 to fix common bugs with @ObservedObject in view initialization
🔸 Example use case:
When initializing a ViewModel directly in a view:

📗 @ObservedObject
Use when the object is injected from elsewhere (e.g., parent view, coordinator)
The view does not own the object—it just observes it
It gets recreated every time the parent view re-renders
🔸 Example use case:
When passing the view model from another source:

✅ Summary:

Use @StateObject when the view creates and owns the object.
Use @ObservedObject when the object is owned elsewhere and just being passed in.

Choosing the right wrapper ensures your state lives as long as you expect and avoids subtle SwiftUI bugs.

Post a Comment

0 Comments