跳到主要内容
哒哒星球DADA PLANET

Skill · 已公开版本

zustand-store-ts · Zustand状态管理写法

提供Zustand存储的类型拆分、选择器订阅、中间件与测试组织等具体写法建议,供前端项目参考。

先看看示例

作者提供的示例,实际效果取决于你的输入和使用工具。

输入

帮我按这些模式设计一个带加载状态和列表操作的Zustand存储。

输出

预期交付:状态与动作类型定义、存储创建代码片段、订阅与测试建议。(编辑说明,非实际运行结果)

方法说明

---
name: zustand-store-ts
description: "Create Zustand stores following established patterns with proper TypeScript types and middleware."
risk: critical
source: community
date_added: "2026-02-27"
---

# Zustand Store

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

## Quick Start

No assets/template.ts is bundled. Adapt the inline examples to the installed Zustand version and actual project types; these are fragments, not a complete application.

## Use subscribeWithSelector for selector subscriptions

```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;
```

## 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();
```

## Subscribe Outside React

```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`

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.