@State vs @StateObject

DheerajRathore
2 min readJul 29, 2023

--

In SwiftUI, “State” and “State Object” are two different property wrappers used to manage and update the data in your views.

@State

A property wrapper type that can read and write a value managed by SwiftUI.

@frozen @propertyWrapper struct State<Value>

Use state as the single source of truth for a given value type that you store in a view hierarchy. State is a property wrapper provided by SwiftUI to manage simple value types like Int, String, Bool, etc., that are mutable and trigger view updates when their values change.

struct ContentView: View {
@State private var increment = 0

var body: some View {
VStack {
Text("Increment: \(increment)")
Button("Increment") {
increment += 1
}
}
}
}

In above example, whenever the increment value changes, SwiftUI will automatically update the view to reflect the updated value.

@StateObject

A property wrapper type that instantiates an observable object.

@frozen @propertyWrapper
struct StateObject<ObjectType> where ObjectType : ObservableObject

Use a state object as the single source of truth for a reference type that you store in a view hierarchy. It is used for managing more complex objects that conform to the ObservableObject protocol. When you use @StateObject, SwiftUI automatically watches for changes to the object's properties and updates the view accordingly.

class UserData: ObservableObject {
@Published var name = "Kate Bell"
}

struct ContentView: View {
@StateObject private var user = UserData()

var body: some View {
VStack {
Text("Hello, \(user.name)!")
Button("Change Name") {
user.name = "Anna Haro"
}
}
}
}

In above example, when the name property of the UserData object gets change, SwiftUI will automatically update the view to display the new name.

Conclusion

It’s essential to consider the scope and the data you are managing when choosing between @State and @StateObject. If the data is specific to a single view and relatively simple, @State is likely the right choice. If the data is more complex, shared, and requires persistence beyond the view's lifespan, @StateObject is the better option.

--

--