zustand-store-ts

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zustand Store

Zustand Store

Create Zustand stores following established patterns with proper TypeScript types and middleware.
遵循既定模式创建Zustand store,搭配规范的TypeScript类型与中间件。

Quick Start

快速开始

Copy the template from assets/template.ts and replace placeholders:
  • {{StoreName}}
    → PascalCase store name (e.g.,
    Project
    )
  • {{description}}
    → Brief description for JSDoc
assets/template.ts复制模板并替换占位符:
  • {{StoreName}}
    → 大驼峰式(PascalCase)的store名称(例如:
    Project
  • {{description}}
    → JSDoc的简短描述

Always Use subscribeWithSelector

务必使用subscribeWithSelector

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

export const useMyStore = create<MyStore>()(
  subscribeWithSelector((set, get) => ({
    // state and actions
  }))
);
typescript
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';

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

Separate State and Actions

分离状态与操作

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

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

export type MyStore = MyState & MyActions;
typescript
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

使用独立选择器

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

// Avoid - re-renders on any state change
const { items, isLoading } = useMyStore();
typescript
// 推荐 - 仅当`items`变化时重新渲染
const items = useMyStore((state) => state.items);

// 避免 - 任何状态变化都会触发重新渲染
const { items, isLoading } = useMyStore();

Subscribe Outside React

在React外部订阅

typescript
useMyStore.subscribe(
  (state) => state.selectedId,
  (selectedId) => console.log('Selected:', selectedId)
);
typescript
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
  1. src/frontend/src/store/
    目录下创建store
  2. src/frontend/src/store/index.ts
    导出
  3. src/frontend/src/store/*.test.ts
    中添加测试