When should we use @StateObject?

When should we use @StateObject?

Do you mean as opposed to @ObservedObject?

The cases where I use StateObject is where I want one instance of an ObservableObject to be available throughout the App particularly where you might update some part of that ObservableObject and want the change to be reflected back in another view. In that case the StateObject is declared in the parent view (the one conforming to App) and is inserted as an .environmentObject on the initial View that is called from the parent. Then in each View where that is required it is added as an @EnvironmentObject

If you mean when do we use @StateObject vs @State, you should always use @State now as it is newer than @StateObject.

Chris has some good points but all I want to add is that in the old observation pattern (where view models conformed to ObservableObject) because they were classes and @State only works for structs, there was another wrapper @StateObject that has the same purpose – updating views whenever its contents change – but for objects.

1 Like