@state
@State
in SwiftUI is a property wrapper used to manage simple, local state within a single view. It enables the view to update its UI whenever the value of the @State
property changes.
Key Characteristics of @State
-
Local State:
@State
is designed for state that belongs exclusively to a single view. It cannot be shared with other views. -
Automatic UI Updates: Changes to a
@State
property automatically trigger the view to re-render, ensuring the UI stays in sync. -
Immutable to the View: Although marked as mutable,
@State
properties are read-only from the perspective of the view body. The changes must be made using the underlying binding.
struct TextInputView: View {
@State private var name: String = ""
var body: some View {
VStack {
TextField("Enter your name", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Text("Hello, \(name)!")
.font(.title)
.padding()
}
.padding()
}
}
Limitations of @State
-
Local to View: Cannot share state with other views. Use
@Binding
,@ObservedObject
, or@EnvironmentObject
for shared state. -
Small, Simple State: Use
@State
for lightweight state only. For more complex or shared state, considerObservableObject
.