SkilVaultSign inStart free

Catalogue / zustand-typed-stores

zustand-typed-stores

Older skill: source not recordedSignedImplements typed Zustand stores for React and vanilla use: selectors, async actions, persistence, slices, custom middleware and isolated tests, including Next.js request and hydration boundaries. Use when the user asks to "create a Zustand store", "stop a component rerendering", "persist store state…
---
name: zustand-typed-stores
description: >-
  Implements typed Zustand stores for React and vanilla use: selectors,
  async actions, persistence, slices, custom middleware and isolated tests,
  including Next.js request and hydration boundaries. Use when the user asks
  to "create a Zustand store", "stop a component rerendering", "persist store
  state", "split the store into slices", "reset stores between tests", or fix
  SSR state leaking between requests. Not for component-local state that no
  other component reads, server-side user state shared across requests, or
  installing packages and persisting data without confirmation.
---

Give shared state an owner, a lifetime and an observable contract

Before choosing an API, inspect the installed Zustand, React, Next.js, TypeScript, test runner and middleware versions, and answer five questions:

  1. Who creates the store?
  2. How long does it live?
  3. Which consumers subscribe?
  4. Which fields may be persisted?
  5. Which side effects can an action perform?

Keep a small local form value or one-component input in React state; a store is justified by shared panels, navigation-spanning preferences or domain operations.

Scope and confirmation

  • Before writing files, changing dependencies, running state-changing code, persisting data or altering test configuration, confirm the exact scope and effects with the user.
  • An explicit implementation or isolated-test request confirms that scope; proceed without repeated prompts.
  • Get fresh confirmation for further installs, destructive cleanup, live requests, persisted-data deletion, externally visible effects or production changes.
  • An async action is not harmless just because it lives in a store.

Report at the end: implementation, integration boundaries, verification results, untested limits. Prefer the project's existing layout — app-specific store inside the app, a shared monorepo package only when consumers really share the contract, or a domain-oriented directory in a single application. These are project files created within the approved scope, not bundled skill dependencies.

Start with lifetime and data ownership

| Need | Design choice | Failure to avoid | |---|---|---| | One component's temporary input | React state | Adding a global lifecycle to a local concern | | Shared client interaction | Focused store with selected subscriptions | Subscribing every component to the entire state | | Multiple distinct domains | Separate stores unless a cross-domain invariant needs one transaction | One giant store with unrelated resets | | Cross-domain atomic update | Composed slices with one functional set | Two unrelated stores briefly exposing an inconsistent result | | Request-specific Next.js data | Factory-created vanilla store, stable provider instance and matching initial data | A module singleton leaking one request's state into another | | Non-React consumer | Vanilla StoreApi and unsubscribe ownership | Calling React hooks outside a component/custom hook | | Durable preference | Deliberately scoped persist middleware | Storing secrets or treating browser storage as trusted input |

Server-boundary rules:

  • Client hooks belong in Client Components.
  • React Server Components fetch server data with the server's async mechanism, use URL parameters for shareable navigation state where suitable, and pass serializable initial values into the client boundary.
  • Server Components never read or mutate a shared client store.
  • For SSR, initialize server/client views consistently and scope user data per request — a 'use client' directive alone guarantees no isolation.

Implement the domain before binding it to a UI

The original core.ts example below models workshop equipment. Key properties:

  • An injected read adapter lets tests supply deterministic data; a production adapter must come from the application within its verified authentication/network contract.
  • Validate parsed data — a TypeScript annotation on response.json() proves nothing.
  • The generation counter stops an older response (including one arriving after reset) from winning; it does not cancel the transport or prove absence of external side effects.
import { createStore } from 'zustand/vanilla';
import type { StoreApi } from 'zustand/vanilla';
export type Equipment = { id: string; label: string };
export type Workshop = {
  title: string; equipment: Equipment[]; status: 'idle' | 'loading' | 'ready' | 'failed';
  error: string | null; mode: 'inspect' | 'edit';
  setTitle: (title: string) => void; setMode: (mode: Workshop['mode']) => void;
  rename: (id: string, label: string) => boolean;
  displayTitle: () => string; load: () => Promise<void>; reset: () => void;
};
export function parseEquipment(value: unknown): Equipment[] {
  if (!Array.isArray(value)) throw new TypeError('Expected equipment array');
  const ids = new Set<string>();
  return value.map(item => {
    if (!item || typeof item !== 'object' || typeof item.id !== 'string' ||
        typeof item.label !== 'string' || !item.id || ids.has(item.id)) {
      throw new TypeError('Invalid or duplicate equipment');
    }
    ids.add(item.id); return { id: item.id, label: item.label };
  });
}
export function createWorkshopStore(read: () => Promise<unknown>, title = 'Workshop') {
  let generation = 0;
  return createStore<Workshop>()((set, get) => ({
    title, equipment: [], status: 'idle', error: null, mode: 'inspect',
    setTitle: next => set({ title: next }),
    setMode: mode => set({ mode }),
    rename: (id, label) => {
      if (get().mode !== 'edit' || !get().equipment.some(item => item.id === id)) return false;
      set(state => ({ equipment: state.equipment.map(item => item.id === id ? { ...item, label } : item) }));
      return true;
    },
    displayTitle: () => `${get().title} (${get().equipment.length} items)`,
    load: async () => {
      const ticket = ++generation;
      set({ status: 'loading', error: null });
      try {
        const equipment = parseEquipment(await read());
        if (ticket === generation) set({ equipment, status: 'ready', error: null });
      } catch (problem) {
        if (ticket === generation) set({ status: 'failed', error: problem instanceof Error ? problem.message : 'Read failed' });
      }
    },
    reset: () => { ++generation; set({ title, equipment: [], status: 'idle', error: null, mode: 'inspect' }); }
  }));
}
export function replaceWorkshop(api: StoreApi<Workshop>, title: string, replace: boolean) {
  const complete: Workshop = { ...api.getState(), title };
  if (replace) api.setState(complete, true);
  else api.setState({ title }, false);
}
export type ItemList<T extends { id: string }> = { items: T[]; add: (item: T) => void; remove: (id: string) => void };
export function createItemList<T extends { id: string }>() {
  return createStore<ItemList<T>>()((set) => ({
    items: [], add: item => set(state => ({ items: [...state.items.filter(x => x.id !== item.id), item] })),
    remove: id => set(state => ({ items: state.items.filter(x => x.id !== id) }))
  }));
}

Set semantics:

  • A partial set merges at the top level; nested objects and arrays need immutable copies.
  • Functional updates calculate from the latest state.
  • A full replacement must contain the complete state, action functions included; resetting only data fields via merge preserves actions.
  • The replaceWorkshop helper branches explicitly on the boolean and builds a complete value, avoiding a broad assertion that can hide missing methods under stricter overloads.
  • Never use the full-replace flag to silently delete action functions.

Typing rules:

  • Use create<State>()(initializer) or createStore<State>()(initializer) when specifying a state type; state participates in input/output positions, so plain inference can be insufficient (this is not a ban on inferred stores).
  • combine can infer from initial data and actions.
  • Do not call get() while constructing initial state; it becomes useful inside actions.
  • State type aliases and interfaces are both legal; module declaration merging uses interface.

For type extraction on releases exporting ExtractState, use that helper. Where it is not exported, this local type gives the same reuse without a circular declaration:

type StateOf<S extends { getState: () => unknown }> = ReturnType<S['getState']>;
// Given an actual store named workshopApi:
// type WorkshopSnapshot = StateOf<typeof workshopApi>;

Reuse the extracted state in props, formatting utilities and tests. Keep the original explicit state type distinct from the extracted alias; never define a state type in terms of the store that needs that type to be created.

Bind one instance and subscribe only to relevant values

The react.tsx module below imports only the core module above. Instance rules:

  • The provider creates a store once per mounted provider; a different request or provider gets a different instance.
  • Initial props seed creation, not automatic later resets — use a deliberate remount key or an approved synchronization action when a new resource should replace the state.
  • Do not pass an arbitrary server function as a prop: the read adapter is client-owned, defined within the client boundary; server-provided initial data must be serializable.
'use client';
import { create, useStore } from 'zustand';
import { useShallow } from 'zustand/react/shallow';
import { createContext, useContext, useState } from 'react';
import type { ReactNode } from 'react';
import { createWorkshopStore } from './core';
import type { Workshop } from './core';
export type WorkshopApi = ReturnType<typeof createWorkshopStore>;
const WorkshopContext = createContext<WorkshopApi | null>(null);
export function WorkshopProvider({ children, read, title }: { children: ReactNode; read: () => Promise<unknown>; title: string }) {
  const [api] = useState(() => createWorkshopStore(read, title));
  return <WorkshopContext.Provider value={api}>{children}</WorkshopContext.Provider>;
}
export function useWorkshop(): Workshop;
export function useWorkshop<T>(selector: (state: Workshop) => T): T;
export function useWorkshop(selector?: (state: Workshop) => unknown) {
  const api = useContext(WorkshopContext);
  if (!api) throw new Error('WorkshopProvider is missing');
  return useStore(api, selector ?? (state => state));
}
export function EquipmentPanel() {
  const title = useWorkshop(state => state.title);
  const count = useWorkshop(state => state.equipment.length);
  const status = useWorkshop(state => state.status);
  const error = useWorkshop(state => state.error);
  const { load, reset } = useWorkshop(useShallow(state => ({ load: state.load, reset: state.reset })));
  return <section aria-label="Equipment">
    <h2>{title}</h2><output aria-label="Equipment count">{count}</output>
    <button onClick={() => void load()} disabled={status === 'loading'}>Load equipment</button>
    <button onClick={reset}>Reset equipment</button>
    {status === 'loading' && <p role="status">Loading equipment</p>}
    {error && <p role="alert">{error}</p>}
  </section>;
}
// Independent browser-only UI state: do not use this module singleton for request-specific SSR data.
type Drawer = { open: boolean; toggle: () => void };
export const useDrawer = create<Drawer>()(set => ({ open: false, toggle: () => set(state => ({ open: !state.open })) }));
export function DrawerButton() {
  const open = useDrawer(state => state.open);
  const toggle = useDrawer(state => state.toggle);
  return <button aria-expanded={open} onClick={toggle}>Tool drawer</button>;
}

Selector discipline:

  • The bounded hook supports an explicit whole-state read for compatibility; normally pass a selector.
  • Primitive selectors and action references minimize irrelevant updates.

Preview shortened. The full SKILL.md is in the pack.