@State Made Easy

The problem
SwiftUI views are structs, which means they’re lightweight and disposable.
Every time something in your app changes, SwiftUI rebuilds parts of the UI from scratch.
Without @State, any data inside the view would reset to its initial value every time it redraws, making it impossible to keep track of things like a counter, toggle, or text input.

What it is
@State is a property wrapper in SwiftUI that allows a view to store and manage its own data over time.
By marking a property with @State, SwiftUI keeps that value outside the view’s struct, so it persists between updates. This way, the view can reactively update itself whenever that state changes.
A @State property must be initialized inside the view where it’s declared.
It’s marked as private to keep the state owned and controlled by that view only, preventing external code from changing it directly and causing unexpected UI behavior.

Local & Private
@State is owned by a single view and acts as that view’s source of truth.
It can be shared with child views in two ways:
- Read-only: Pass the value directly. The child can read it but not change it.
- Read & write: Pass a binding ($state). The child can read and update the value. I’ll cover @Binding in a separate post for a deeper look at two-way data sharing.

Lifecycle
@State keeps its value between view updates, even though SwiftUI recreates the view’s struct many times.
However, if the view leaves the hierarchy and comes back, the state resets to its initial value.

Wrapping up
@State is the simplest way to make your SwiftUI views dynamic and interactive.
It keeps local data alive while the view is on screen and automatically updates the UI when that data changes.
Start small, like counters, toggles, or text inputs, and you’ll quickly see how powerful this tiny property wrapper really is. 🚀