Naalya Handbook

Client state

What lives in Zustand versus React Query, and how the persisted stores for auth, theme, impersonation and panels work.

Use this page when you decide where a new piece of Education Hub state belongs. Server data goes in React Query; browser-local state goes in Zustand. Mixing the two is a fast way to write a confusing bug.

  • Server data lives in React Query: the list of students, the current user's profile, a department's roster. React Query fetches, caches, dedupes, and invalidates it. Do not store the result anywhere else.
  • Client-local state lives in Zustand: whether the side panel is open, whether the theme is dark, who you are impersonating. It covers UI, preferences, and session bookkeeping.

Server data never goes in Zustand

Never copy server data into a store. React Query already owns the lifecycle of anything that came from the API: when it is stale, when to refetch, and how to invalidate it after a mutation. A snapshot in a store is a second copy that nobody keeps in sync, and the UI starts showing yesterday's roster.

Before you add a field to a store, ask: does this come from the API? If it does, use a query hook (see The data layer). Only purely local state, such as a toggle, a preference, or a transient bit of session state, belongs in Zustand.

The dividing line

Zustand = client-local / UI / persistent state. React Query = server data. Auth tokens are the one edge case. A token is not server data you refetch; it is a credential the client holds, so it lives in a Zustand store. The user it identifies (getMe) is server data, so that lives in React Query.

Persisted stores: One pattern, named keys

Every client-state store uses persist with a named localStorage key. Each is a Zustand create() wrapped in the persist middleware. The key gives each store a stable, readable home in devtools that survives reloads.

The auth store is the smallest example, so start there. It holds two strings and the two actions that set or clear them:

src/components/providers/auth.provider.tsx
export const useAuth = create<AuthState>()(
  persist(
    (set) => ({
      token: null,
      refreshToken: null,
      setTokens: (token, refreshToken) => set({ token, refreshToken }),
      clearTokens: () => set({ token: null, refreshToken: null }),
    }),
    { name: tokenKey, storage: createJSONStorage(() => localStorage) },
  ),
)

Two lines matter:

  • createJSONStorage(() => localStorage) makes the state survive a refresh. Without it, the store is in memory only and a reload signs you out.
  • name: tokenKey is the localStorage key. It resolves to "auth-token". In devtools, expand Local Storage to read or wipe any store by its name, which helps when you debug a stuck session.

Reset a stuck store by deleting its key

Each store declares its name, so the Application tab in devtools shows the app's whole client state: auth-token, bellefull-theme, impersonation-origin, sidepanel-state. To reset one, delete its key and reload.

Stores: Auth, theme, impersonation, side panel

The Hub has four persisted client-state stores. Each owns one slice of local state.

StorelocalStorage keyHoldsFile
Authauth-tokentoken and refreshToken, with setTokens and clearTokens. The API client reads tokens from here.src/components/providers/auth.provider.tsx
Themebellefull-themeOne 'light' | 'dark' value, with toggleTheme and setTheme. A small provider syncs it to a class on <html>.src/components/providers/theme.provider.tsx
Impersonationimpersonation-originA stash-and-swap store that lets an admin step into another user's session and back out. See the guard in Guards in actions.src/components/providers/impersonation.provider.tsx
Side panelsidepanel-stateWhether a panel is open, its size, and which panel is current.src/components/side-panels/_registry/use-sidepanel.ts

How tokens are minted, refreshed, and cleared is on Sessions and tokens. The theme store is a short example of the pattern:

src/components/providers/theme.provider.tsx
export const useTheme = create<ThemeProvider>()(
  persist(
    (set) => ({
      theme: 'light',
      toggleTheme: () =>
        set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })),
      setTheme: (theme) => set({ theme }),
    }),
    { name: 'bellefull-theme', storage: createJSONStorage(() => localStorage) },
  ),
)

Theme flash: a pre-paint script applies the class first

A pre-paint script in __root.tsx reads bellefull-theme from localStorage and applies the class before React renders. Without it, a cold load paints light and then snaps to dark, because the theme provider's useEffect runs after React renders. The store stays the source of truth; the script only gets there first.

Partialize: Persist only durable fields

Use partialize to choose which fields reach localStorage. The side-panel store holds fields worth remembering across reloads (open or closed, size) and transient validation fields (contextValid, missingContext) that should not be written. partialize returns the slice to persist:

src/components/side-panels/_registry/use-sidepanel.ts
{
  name: 'sidepanel-state',
  storage: createJSONStorage(() => localStorage),
  partialize: (state) => ({
    isOpen: state.isOpen,
    panelSize: state.panelSize,
    currentPanel: state.currentPanel,
    currentPanelProps: state.currentPanelProps,
    overlay: state.overlay,
  }),
}

Fields in the returned object are persisted; fields left out are recomputed on each load. Use partialize whenever a store mixes durable preferences with transient, derived state.

Guards in actions

Read the current state with get() before a transition mutates it. Zustand actions receive get() alongside set(), which lets an action refuse a transition that would corrupt the store. Two stores rely on this.

The side-panel togglePanel refuses to open when there's nothing to show:

src/components/side-panels/_registry/use-sidepanel.ts
togglePanel: () => {
  const { isOpen, currentPanel } = get()
  if (!currentPanel) return // no-op if there's no panel to show
  set({ isOpen: !isOpen })
},

Impersonation is the sharper example. Its start action stashes the admin's real tokens as origin, then swaps in the target user's tokens. A second start while already impersonating would stash the impersonation tokens as origin, and the admin's real session would be lost. One get() guard prevents that:

src/components/providers/impersonation.provider.tsx
start: ({ accessToken, refreshToken, targetName }) => {
  if (get().isImpersonating) return // guard re-entry
  const current = getStoredAuth()
  if (current.token && current.refreshToken) {
    set({ origin: { token: current.token, refreshToken: current.refreshToken } })
  }
  setStoredAuth(accessToken, refreshToken)
  set({ isImpersonating: true, targetName })
},

Open every transition action with a get() check

Any action that swaps, stashes, or toggles based on the current value needs a get() check first. The impersonation guard is load-bearing: without if (get().isImpersonating) return, a double-click on impersonate destroys the admin's session with no way back. When you write a transition action, ask what happens if it fires twice.

Where to go next

On this page