State Management

Learn how to manage application state in Shaft using Swift’s Observation framework.

What is State?

State is any data that can change over time and affects what your UI displays. In Shaft, state management is beautifully simple thanks to Swift’s @Observable macro.

The @Observable Macro

The @Observable macro automatically makes your classes observable, enabling automatic UI updates when properties change.

Basic Usage

Observable Counter

How It Works

  1. Mark your class with @Observable
  2. Read the property in your widget’s build() method
  3. When the property changes, Shaft automatically rebuilds the widget

No manual subscriptions. No setState. It just works!

Complex State

@Observable works perfectly with nested objects and collections:

Shopping List

Deep Observation

@Observable automatically tracks changes at any depth:

  • Modifying shoppingList.items triggers updates
  • Changing item.quantity triggers updates
  • The computed total property automatically recalculates

StatefulWidget Alternative

While @Observable is recommended, you can still use traditional StatefulWidget when needed:

StatefulWidget State

When to Use StatefulWidget

  • Widget-level state: Button pressed state, animation state, UI-only state
  • Local interactions: Toggle switches, dropdown menus, temporary UI state
  • Widget-specific behavior: Focus management, scroll position, selection state

When to Use @Observable

  • Application state: User data, shopping cart items, authentication status
  • Shared state: Data that multiple widgets need to access
  • Business logic: Counter values, form data, API responses
  • Global state: Settings, user preferences, app configuration

Next Steps

Additional Resources