In this post, you’ll learn:
- The difference between @State, @Binding, @ObservedObject, @EnvironmentObject, and @StateObject.
- When to use each property wrapper.
- How to share data between views effectively.
By the end, you’ll confidently manage state in SwiftUI like a pro. 🚀
Why Does State Matter?
- Without state management → UI won’t update when data changes.
- With proper state management → Views react dynamically to user actions.
Let’s explore the different ways to manage state in SwiftUI.
Use @State for small, private variables that belong to a single view.
Example: Counter App
- Use @State for simple values (e.g., numbers, booleans, strings).
- It should not be used for complex objects or shared data.
- SwiftUI automatically updates the UI when the @State value changes.
If a child view needs to modify a @State variable, use @Binding.
Example: Toggle Button
- Use @Binding when a child view needs to modify a parent’s state.
- The @State variable in ParentView remains the single source of truth.
If a view owns an object and should initialize it only once, use @StateObject.
Example: Timer App
- Use @StateObject for new instances of ObservableObject.
- SwiftUI ensures the object persists correctly during view updates.
- Best for managing side effects like API calls, timers, or large datasets.
If a parent creates an object and wants to share it with multiple child views, use @ObservedObject.
Example: Sharing Data Across Views
- Use @ObservedObject when a parent creates the object and shares it with children.
- Changes in @Published properties trigger UI updates.
- Best for passing shared data between views.
For app-wide state, use @EnvironmentObject.
Example: User Authentication
- Use @EnvironmentObject for app-wide shared data.
- No need to pass data manually through multiple views.
- Best for user settings, authentication, and app-wide preferences.
When to Use Which Property Wrapper?
- @State — Local state for simple values.
- @Binding — Passing state to child views.
- @StateObject — Owning an object in a view.
- @ObservedObject — Sharing an object between views.
- @EnvironmentObject — Global state for the entire app.