Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท State and Storage

State Management in Ionic Apps

Choose where state lives in an Ionic app: component state, shared services or stores, signals, NgRx or Zustand, and avoid stale data when pages stay alive in the stack.

State is any data that changes while the app runs: the signed-in user, the list of notes, a filter, a draft. In a small page you keep it in the component. As soon as two pages need the same data, you need a shared place for it. Ionic does not ship its own state library. It works with whatever your framework uses, so this lesson focuses on the decisions and on one idea that is special to Ionic: pages stay alive in the navigation stack.

Types of state

Kind Example Where it lives
Local UI state "is the accordion open" the component
Shared app state notes, settings, current user a service or store
Server data the list returned by /api/notes a cache layer
URL state the selected note id the route
Persistent state theme, last login Preferences or SQLite

Putting each kind in the right place prevents most bugs. The most common mistake is copying server data into many components and then having to keep them in sync.

Pages stay alive

On the web, leaving a page destroys it. In Ionic's stack navigation, going from a list to a detail page keeps the list mounted but hidden, so that going back is instant and keeps the scroll position. A consequence: the list's ngOnInit (or React useEffect([])) does not run again when you return. If the detail page changed a note, the list will show old data unless it reads from shared state or refreshes on a lifecycle event.

flowchart LR
  A["List page"] -->|"push"| B["Detail page"]
  B -->|"edit and save"| S[("Shared store")]
  B -->|"back (pop)"| A
  S -->|"list re-renders"| A

Both pages read the same store, so the list updates without reloading.

Ionic also gives lifecycle hooks for refreshing: ionViewWillEnter in Angular, useIonViewWillEnter in React and onIonViewWillEnter in Vue. Use them for cheap refreshes, but prefer shared state so that no refresh is needed.

Shared state with a service (Angular)

With Angular, a root-provided service holding signals is the lightest solution:

TypeScript
import { Injectable, computed, signal } from '@angular/core';

export interface Note { id: number; title: string; done: boolean }

@Injectable({ providedIn: 'root' })
export class NotesStore {
  private readonly _notes = signal<Note[]>([]);
  readonly notes = this._notes.asReadonly();
  readonly openCount = computed(() => this._notes().filter(n => !n.done).length);

  add(title: string) {
    this._notes.update(list => [...list, { id: Date.now(), title, done: false }]);
  }
  toggle(id: number) {
    this._notes.update(list => list.map(n => (n.id === id ? { ...n, done: !n.done } : n)));
  }
}

Components inject the store and read store.notes() in templates. State is changed only through methods, and always by creating new arrays and objects, so change detection sees the update. Larger apps with many effects can step up to NgRx or its signal store; the idea stays the same.

Shared state with React

React Ionic apps use context for simple cases, and a small store such as Zustand when state grows:

TSX
import { create } from 'zustand';

interface NotesState {
  notes: { id: number; title: string; done: boolean }[];
  add: (title: string) => void;
  toggle: (id: number) => void;
}

export const useNotes = create<NotesState>((set) => ({
  notes: [],
  add: (title) => set((s) => ({ notes: [...s.notes, { id: Date.now(), title, done: false }] })),
  toggle: (id) => set((s) => ({ notes: s.notes.map((n) => (n.id === id ? { ...n, done: !n.done } : n)) })),
}));

// in a component
const notes = useNotes((s) => s.notes);   // re-renders only when notes change

Vue apps use Pinia in the same way. Pick the idiom of your framework; none is "the Ionic way".

The core pattern, framework free

All of these libraries implement one pattern: a value, a way to change it, and a way to subscribe. This stand-in is a complete store you can read in a minute.

JS A minimal reactive store

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Derived state and immutability

Never store something you can compute. openCount above is derived from notes; storing it separately invites mismatch. And never mutate: notes.push(x) changes the array in place, so code that compares references (frameworks, memoized selectors) believes nothing changed.

JS Why mutation breaks change detection

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Server state

Lists fetched from an API are a cache, not your own state. Libraries such as TanStack Query handle loading, errors, refetching and invalidation. Whatever you use, keep one source of truth per resource and decide when it is stale. Offline First and Sync covers saving that cache on the device.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You return to a list page after editing an item on the detail page, and the list still shows old data. Why?

    Ionic keeps stack pages alive. Read shared state or refresh in ionViewWillEnter.
  2. 2. Which is derived state and should not be stored separately?

    A count can be computed from the list, so storing it can only go out of sync.
  3. 3. Why create a new array instead of using push()?

    An in-place mutation keeps the same reference, so subscribers may not notice the change.
  4. 4. Which state belongs in the URL?

    Ids that identify what is shown belong in the route, so links and back navigation work.

Summary

  • Place each kind of state where it belongs: component, store, cache, URL or storage.
  • Ionic keeps pages alive, so share state or refresh on view lifecycle hooks.
  • Signals (Angular), Zustand or context (React) and Pinia (Vue) all implement value, update and subscribe.
  • Derive instead of duplicating; update immutably.
  • Treat server data as a cache with a clear refresh rule.

Next: Storage, Preferences and SQLite