> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# State management

Two kinds of state:

| Kind             | Owner                   | Persistence     | Examples                            |
| ---------------- | ----------------------- | --------------- | ----------------------------------- |
| **Client state** | `zustand`               | Optional MMKV   | onboarding flag, session, filter UI |
| **Server state** | `@tanstack/react-query` | In-memory cache | tracks list, track detail           |

See [data-fetching.md](/docs/data-fetching.md) for server state.

## Layer overview

```mermaid
flowchart LR
  screens --> store["features/&lt;x&gt;/store.ts"]
  store --> zustand
  zustand -->|optional| persist[persist middleware]
  persist --> jsonStorage[createJSONStorage]
  jsonStorage --> mmkvStorage["mmkvStorage (StateStorage)"]
  mmkvStorage --> mmkvInstance["MMKV instance<br/>(src/core/services/mmkv.ts)"]
```

## MMKV adapter

A single MMKV instance backs all persisted stores. The adapter implements zustand's `StateStorage` so it plugs into the `persist` middleware via `createJSONStorage`.

```ts
// src/core/services/mmkv.ts
import { createMMKV } from 'react-native-mmkv';
import type { StateStorage } from 'zustand/middleware';

export const storage = createMMKV({ id: 'app' });

export const mmkvStorage: StateStorage = {
  getItem: (name) => storage.getString(name) ?? null,
  setItem: (name, value) => storage.set(name, value),
  removeItem: (name) => storage.remove(name),
};
```

Why one instance: smaller binary footprint, shared OS-level handle, and a single place to swap to encrypted MMKV later (`createMMKV({ id: 'app', encryptionKey: '...' })`).

## Persisted vs ephemeral stores

```mermaid
flowchart TB
  subgraph persisted [Persisted - survives app restart]
    onb["useOnboardingStore<br/>key: onboarding"]
    auth["useAuthStore<br/>key: auth"]
    ent["useEntitlementsStore<br/>key: entitlements"]
    rc["useRemoteConfigStore<br/>key: remote-config<br/>(last-known-good cache)"]
  end
  subgraph ephemeral [Ephemeral - in-memory only]
    tracksUi["useTracksStore<br/>filters + selectedId"]
    pianoUi["usePianoUiStore<br/>octave + selected song"]
  end
  persisted --> mmkv[(MMKV)]
  ephemeral --> memory[(RAM)]
```

Rule of thumb: persist only what you'd want a returning user to see (their onboarding completion, their session). Never persist server-derived data — that's React Query's job and it has TTL/staleness rules.

If a persisted store sets `version`, it **must** also set `migrate` (identity is fine when the shape did not change). Without `migrate`, zustand logs `State loaded from storage couldn't be migrated since no migrate function was provided` and discards any snapshot written at a lower version — including older installs that stored `version: 0` before `version` was added.

Exception: `useRemoteConfigStore` caches the last successful Firebase Remote Config snapshot under MMKV key `remote-config`. Product flags (`enableIAP`, `fs_logic`, …) must not snap back to source-code defaults when a launch is offline or the 8s fetch times out. A successful fetch rebuilds from in-app defaults + Firebase-resolved params (`remote` console values and RC `defaultConfig`); SDK `static` keys stay on the in-app schema defaults. The fetch-attempt flag `hydrated` is in-memory only.

## Store anatomy — persisted

```ts
// src/features/onboarding/store.ts
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { mmkvStorage } from '@services/mmkv';

interface OnboardingState {
  hasCompleted: boolean;
  complete: () => void;
  reset: () => void;
}

export const useOnboardingStore = create<OnboardingState>()(
  persist(
    (set) => ({
      hasCompleted: false,
      complete: () => set({ hasCompleted: true }),
      reset: () => set({ hasCompleted: false }),
    }),
    {
      name: 'onboarding', // <- MMKV key
      storage: createJSONStorage(() => mmkvStorage),
    },
  ),
);
```

## Store anatomy — ephemeral

```ts
// src/features/tracks/store.ts
import { create } from 'zustand';
import type { TrackFilters } from '@features/tracks/types';

interface TracksUiState {
  filters: TrackFilters;
  selectedId: string | null;
  setSearch: (search: string) => void;
  setDifficulty: (d: TrackFilters['difficulty']) => void;
  setSelectedId: (id: string | null) => void;
  reset: () => void;
}

export const useTracksStore = create<TracksUiState>((set) => ({
  filters: { search: '', difficulty: 'all' },
  selectedId: null,
  setSearch: (search) => set((s) => ({ filters: { ...s.filters, search } })),
  setDifficulty: (difficulty) => set((s) => ({ filters: { ...s.filters, difficulty } })),
  setSelectedId: (id) => set({ selectedId: id }),
  reset: () => set({ filters: { search: '', difficulty: 'all' }, selectedId: null }),
}));
```

## Hydration & boot

`zustand/persist` is synchronous when paired with MMKV, so the `<Stack.Protected>` guards in `app/_layout.tsx` can read `hasCompleted` and `session` on first render and pick the right group immediately. Splash gating is handled separately by `expo-font` + `SplashScreen.hideAsync()` in the same root layout — see [routing.md](/docs/routing.md).

```mermaid
sequenceDiagram
  participant Root as app/_layout.tsx
  participant OnbStore as useOnboardingStore
  participant AuthStore as useAuthStore
  participant Mmkv as MMKV
  participant Stack as <Stack.Protected>

  Root->>OnbStore: read hasCompleted
  OnbStore->>Mmkv: getString("onboarding")
  Mmkv-->>OnbStore: JSON
  Root->>AuthStore: read session
  AuthStore->>Mmkv: getString("auth")
  Mmkv-->>AuthStore: JSON
  Root->>Stack: evaluate guards, mount first match
```

## Partializing what you persist

For sensitive or derived state, use `partialize` to whitelist the keys that hit disk. `useAuthStore` only persists `session`:

```ts
persist(
  (set) => ({ ... }),
  {
    name: 'auth',
    storage: createJSONStorage(() => mmkvStorage),
    partialize: (state) => ({ session: state.session }),
    onRehydrateStorage: () => (state) => state?.setHydrated(),
  },
);
```

## Clearing state

| Goal                          | How                                                                                                                             |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| Sign out                      | `performSignOut()` from `@features/auth/signOut` — wipes session, ephemeral UI stores, and React Query cache. Keeps onboarding. |
| Reset onboarding flow (debug) | `useOnboardingStore.getState().reset()` + `useTutorialStore.getState().reset()` + `usePaywallStore.getState().close()`          |
| Wipe everything               | `storage.clearAll()` (`@services/mmkv`) — destroys both keys                                                                    |

The Profile screen exposes a debug "Reset onboarding flow" action so QA can repeat the full onboarding → paywall → tutorial sequence without reinstalling.

## When NOT to use a zustand store

- The state is server-owned → use a `useQuery`.
- The state belongs to one component → use `useState`.
- The state is derived → compute in `useMemo` from inputs.
- The state is form-local → keep in the component or a form library.

***

<small>Source: [`docs/state-management.md`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/state-management.md)</small>
