What is @State in SwiftUI?

A Beginner's Guide to @State in SwiftUI for Building Dynamic User Interfaces

ยท

2 min read

What is @State in SwiftUI?

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 WrapperUse Case
@StateSimple state local to a single view.
@BindingTwo-way binding between a child and parent view.
@StateObjectReference type object, with ownership by the view.
@ObservedObjectReference type object, observed by the view but not owned.
@EnvironmentObjectShared object injected into the environment for app-wide accessibility.

When Not to Use:

For shared or persistent data, use @StateObject, @ObservedObject, or @EnvironmentObject.

ย