State Fundamentals

Local vs shared state, lifting state up, derived state, unidirectional data flow, and the difference between UI state and server data.

Beginner · about 5 hours · difficulty 3/5

Learn first: Components, Props & Styling

State is any data that can change and affects what is on screen. Most "state management" confusion disappears once you classify your state.

Kinds of state

  • Local UI state: is this dropdown open, what is typed in this field. Keep it in the component (useState, StatefulWidget, remember, @State).
  • Shared app state: current user, theme, cart contents. Lives above the screens that need it.
  • Server state: data owned by a backend (products, messages). It is a *cache* that can go stale; treat it differently (see networking).
  • Persisted state: survives app restarts (settings, drafts).
  • Navigation state: which screen is showing, owned by the router.

Principles

  • Single source of truth: each piece of data lives in exactly one place.
  • Lift state up to the nearest common parent when two components need it.
  • Derive, don't duplicate: compute totals and filtered lists from state rather than storing them separately.
  • Unidirectional flow: state flows down, events flow up, and updates happen in one place.

Pitfalls

Putting everything in a global store too early creates tangled code. Start local, lift when needed.

Good enough to move on: for any screen you can say which state is local, shared, server or persisted, and where each lives.

Key concepts

  • Local component state
  • Lifting state up
  • Derived state
  • Unidirectional data flow
  • Server state vs client state
  • Immutability and state updates

Mini project

Build a shopping cart across two tabs (catalogue and cart) where totals are derived, not stored, and item counts stay in sync.

Check yourself

Why is storing both a list of items and a separate itemCount in state a bug waiting to happen?

Free resources