Skip to main content

zustand-store-ts

Create Zustand stores with TypeScript, subscribeWithSelector middleware, and proper state/action separation. Use when building React state management, creating global stores, or implementing reactive state patterns with Zustand.

Microsoft
General

Zustand Store

Create Zustand stores following established patterns with proper TypeScript types and middleware.

Quick Start

Copy the template from assets/template.ts and replace placeholders:

  • {{StoreName}} → PascalCase store name (e.g., Project)

  • {{description}} → Brief description for JSDoc


Always Use subscribeWithSelector

import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';

export const useMyStore = create<MyStore>()(
  subscribeWithSelector((set, get) => ({
    // state and actions
  }))
);

Separate State and Actions

export interface MyState {
  items: Item[];
  isLoading: boolean;
}

export interface MyActions {
  addItem: (item: Item) => void;
  loadItems: () => Promise<void>;
}

export type MyStore = MyState & MyActions;

Use Individual Selectors

// Good - only re-renders when `items` changes
const items = useMyStore((state) => state.items);

// Avoid - re-renders on any state change
const { items, isLoading } = useMyStore();

Subscribe Outside React

useMyStore.subscribe(
  (state) => state.selectedId,
  (selectedId) => console.log('Selected:', selectedId)
);

Integration Steps

  1. Create store in src/frontend/src/store/
  2. Export from src/frontend/src/store/index.ts
  3. Add tests in src/frontend/src/store/*.test.ts