What is @State in SwiftUI?
A Beginner's Guide to @State in SwiftUI for Building Dynamic User Interfaces
The @State
property wrapper in SwiftUI is used to manage local state within a view. It enables reactive updates, meaning the view will automatically re-render when the state changes.
Key Points:
View-Specific: Only the view owning the
@State
variable can modify it.Reactive: Changes to
@State
trigger a UI update.Lightweight: Ideal for simple, private states like toggles or counters.
Example:
import SwiftUI
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
count += 1
}
}
}
}
Here, @State
makes count
reactive, so the UI updates whenever the button is pressed.
When Should You Use @State
?
Use @State
for managing simple and private state within a view. Some common examples include:
Tracking toggle switches or checkboxes.
Storing user input from a
TextField
.Managing counters or progress values.
Comparison with Other Property Wrappers
Property Wrapper | Use Case |
@State | Simple state local to a single view. |
@Binding | Two-way binding between a child and parent view. |
@StateObject | Reference type object, with ownership by the view. |
@ObservedObject | Reference type object, observed by the view but not owned. |
@EnvironmentObject | Shared object injected into the environment for app-wide accessibility. |
When Not to Use:
For shared or persistent data, use @StateObject
, @ObservedObject
, or @EnvironmentObject
.
ย