Agent skill

State Management

by mobazha in mobazha/mobazha-unified

Guide for Zustand state management patterns in Mobazha including store design, middleware usage, selectors, persistence, and integration with React Query.

MPL-2.0Auto-check passedFrontend & Design

Install State Management

skills CLI
$ npx skills add mobazha/mobazha-unified --skill state-management -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install mobazha/mobazha-unified state-management --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/mobazha/mobazha-unified.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.cursor/skills/state-management .claude/skills/state-management && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
state-management
GitHub stars
165
Token cost
~1.7k tokens
SKILL.md length
134 words
Files
1
Skills in repo
29
Repo updated
First seen
Licence
MPL-2.0

At a glance

Guide for Zustand state management patterns in Mobazha including store design, middleware usage, selectors, persistence, and integration with React Query.

  • Works in 2 steps: 按领域划分 → Server State vs Client State
  • Modifying stores
  • SKILL.md covers 现有 Store 一览, Store 设计原则, 标准 Store 模板 and Middleware 使用, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

State Management is an agent skill from mobazha/mobazha-unified. Guide for Zustand state management patterns in Mobazha including store design, middleware usage, selectors, persistence, and integration with React Query. Use when creating or modifying stores, or working with state management, "状态管理", "Zustand", "Store", "全局状态", "持久化".

Its SKILL.md is about 1.7k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Frontend & Design, covering State management. It works with Zustand and TanStack. The repository describes itself as: Open-source commerce frontend for storefronts, marketplaces, checkout, and seller management. The licence is MPL-2.0.

When your agent uses it

  • Modifying stores
  • Working with state management

Example prompts

  • “Zustand”
  • “/state-management”

Workflow steps

2 steps, taken from the step headings in SKILL.md.

  1. 按领域划分
  2. Server State vs Client State

What it can do on your machine

Read from SKILL.md and the folder at commit 156c699. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

State Management loads about 1.7k tokens when it runs. Until then it costs about 72 tokens; SKILL.md has 134 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~72
When it runs · the whole SKILL.md, loaded when a task matches
~1.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from mobazha/mobazha-unified at commit 156c699, republished under its MPL-2.0 licence (© mobazha). 134 words, ~1,685 tokens.

Download SKILL.mdSave it as .claude/skills/state-management/SKILL.md (or your agent's skills folder).
name
state-management
description
Guide for Zustand state management patterns in Mobazha including store design, middleware usage, selectors, persistence, and integration with React Query. Use when creating or modifying stores, or working with state management, "状态管理", "Zustand", "Store", "全局状态", "持久化".

状态管理指南

Mobazha 项目基于 Zustand 的状态管理模式和最佳实践。

现有 Store 一览

Store文件持久化用途
useUserStoreuserStore.ts✅ 部分用户认证、profile
useCartStorecartStore.ts✅ 全部购物车
useWalletStorewalletStore.ts❌钱包余额、交易
useCurrencyStorecurrencyStore.ts✅汇率、货币转换
useChatStorechatStore.ts❌Matrix 聊天状态
useNotificationStorenotificationStore.ts❌通知
useRoleStoreroleStore.ts❌用户角色

Store 设计原则

1. 按领域划分

每个 Store 对应一个业务领域,保持单一职责:

typescript
// ✅ 好:职责清晰
useCartStore; // 只管购物车
useWalletStore; // 只管钱包

// ❌ 差:职责混乱
useAppStore; // 什么都放
2. Server State vs Client State
类型管理方式示例
Server State(后端数据)React Query / API 请求订单列表、商品详情
Client State(本地状态)Zustand Store购物车、UI 偏好、聊天状态
Derived State(派生数据)useMemo / Store 计算属性购物车总价、筛选后的列表
typescript
// ✅ Server state 用 hook(内部可能用 React Query 或直接 API)
const { orders, isLoading } = useOrders();

// ✅ Client state 用 Store
const cartItems = useCartStore(state => state.items);

标准 Store 模板

typescript
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

// 1. 定义接口
interface ExampleState {
  // 状态
  items: Item[];
  selectedId: string | null;
  isLoading: boolean;
  error: string | null;

  // 动作
  fetchItems: () => Promise<void>;
  addItem: (item: Item) => void;
  removeItem: (id: string) => void;
  selectItem: (id: string | null) => void;
  clearError: () => void;

  // 计算属性
  getItemCount: () => number;
  getItemById: (id: string) => Item | undefined;
}

// 2. 创建 Store
export const useExampleStore = create<ExampleState>()(
  devtools(
    persist(
      (set, get) => ({
        // 初始状态
        items: [],
        selectedId: null,
        isLoading: false,
        error: null,

        // 异步动作
        fetchItems: async () => {
          try {
            set({ isLoading: true, error: null });
            const items = await exampleApi.getItems();
            set({ items, isLoading: false });
          } catch (err) {
            set({
              error: err instanceof Error ? err.message : '加载失败',
              isLoading: false,
            });
          }
        },

        // 同步动作
        addItem: item =>
          set(state => ({
            items: [...state.items, item],
          })),

        removeItem: id =>
          set(state => ({
            items: state.items.filter(i => i.id !== id),
          })),

        selectItem: id => set({ selectedId: id }),

        clearError: () => set({ error: null }),

        // 计算属性
        getItemCount: () => get().items.length,
        getItemById: id => get().items.find(i => i.id === id),
      }),
      {
        name: 'mobazha-example-storage', // localStorage key
        partialize: state => ({
          items: state.items, // 只持久化必要的字段
          // 不持久化 isLoading, error 等临时状态
        }),
      }
    ),
    { name: 'ExampleStore' } // DevTools 中显示的名称
  )
);

// 3. 导出选择器
export const selectItems = (state: ExampleState) => state.items;
export const selectLoading = (state: ExampleState) => state.isLoading;
export const selectError = (state: ExampleState) => state.error;

Middleware 使用

devtools(所有 Store 必须使用)
typescript
// 在 Redux DevTools 中可视化状态变化
devtools(storeCreator, { name: 'StoreName' });
persist(需要持久化的 Store)
typescript
persist(storeCreator, {
  name: 'mobazha-xxx-storage', // localStorage key,统一 mobazha- 前缀
  partialize: state => ({
    // 只持久化必要字段
    items: state.items,
    preferences: state.preferences,
    // ❌ 不要持久化:isLoading, error, 临时 UI 状态
  }),
});
Middleware 组合顺序
typescript
// 标准顺序:devtools 在最外层
create<State>()(
  devtools(         // 最外层
    persist(        // 内层(可选)
      (set, get) => ({ ... })
    )
  )
);

选择器优化

避免不必要的重渲染
typescript
// ❌ 差:每次 store 任何变化都会重渲染
const { items, isLoading, error } = useCartStore();

// ✅ 好:只订阅需要的字段
const items = useCartStore(state => state.items);
const isLoading = useCartStore(state => state.isLoading);

// ✅ 更好:使用导出的选择器
const items = useCartStore(selectCartItems);

// ✅ 组合选择器(需要 shallow 比较)
import { useShallow } from 'zustand/react/shallow';

const { items, total } = useCartStore(
  useShallow(state => ({
    items: state.items,
    total: state.getTotal(),
  }))
);
选择器命名规范
typescript
// 前缀 select + 描述
export const selectCartItems = (state: CartState) => state.items;
export const selectCartTotal = (state: CartState) => state.getTotal();
export const selectIsCartEmpty = (state: CartState) => state.items.length === 0;

错误处理模式

项目统一的异步动作错误处理:

typescript
fetchData: async () => {
  try {
    set({ isLoading: true, error: null });
    const data = await apiCall();
    set({ data, isLoading: false });
  } catch (err) {
    set({
      error: err instanceof Error ? err.message : '未知错误',
      isLoading: false,
    });
  }
},

何时创建新 Store

场景建议
多个页面/组件共享的客户端状态✅ 创建新 Store
单个页面内的临时状态❌ 用 useState
从后端获取的数据❌ 用 API hook(useOrders 等)
全局 UI 状态(主题、语言)✅ Store + persist
表单状态❌ 用 useState 或表单库

测试模式

typescript
import { act } from '@testing-library/react';

describe('useCartStore', () => {
  beforeEach(() => {
    // 重置 store 状态
    useCartStore.setState({
      items: [],
      isLoading: false,
      error: null,
    });
  });

  it('应正确添加商品', () => {
    act(() => {
      useCartStore.getState().addItem(mockItem);
    });

    expect(useCartStore.getState().items).toHaveLength(1);
  });
});

快速检查清单

  • 新 Store 是否只包含客户端状态?
  • 是否使用 devtools middleware?
  • 持久化时是否用 partialize 排除临时状态?
  • 选择器是否精确订阅(避免整个 store 订阅)?
  • localStorage key 是否使用 mobazha- 前缀?
  • 异步动作是否有统一的 error/loading 处理?

© mobazha, MPL-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .cursor/skills/state-management of mobazha/mobazha-unified.

Open the folder on GitHubat commit 156c699

Compare with similar skills

State Management next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

State Management compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
State Management this skillmobazha/mobazha-unified165—~1.7kAutomated safety check: PassMPL-2.0
React State Managementinvolvex/youtube-music-cli45613 repos~3kAutomated safety check: PassMIT
Nextjs15 Initbear2u/my-skills933—~2.4kAutomated safety check: PassNone
Opik Frontend Patternscomet-ml/opik22k—~1.1kAutomated safety check: PassApache-2.0
State Managementemanueleielo/deepagents-open-lovable111—~1.7kAutomated safety check: PassNone
React ExpertJeffallan/claude-skills12k—~1.4kAutomated safety check: PassMIT

Similar skills

  • React State Management

    involvex/youtube-music-cli

    Master modern React state management with Redux Toolkit, Zustand, Jotai, and React Query.

    456 GitHub starsUsed in 13 repos~3k tokens
    Frontend & DesignAuto-check passed
  • Nextjs15 Init

    bear2u/my-skills

    A skill your agent uses when user wants to create a new Next.js 15 project (Todo/Blog/Dashboard/E-commerce/Custom domain) with App Router, ShadCN, Zustand, Tanstack Query, and modern Next.js stack

    933 GitHub stars~2.4k tokensUpdated 3 mo ago
    Frontend & DesignAuto-check passed
  • Sets the conventions for the Opik React frontend: TanStack Query for data, Zustand for shared state, one-way layer imports and a fix for Google Translate crashes.

    22k GitHub stars~1.1k tokensUpdated today
    Frontend & DesignAuto-check passed
  • State Management

    emanueleielo/deepagents-open-lovable

    State management patterns - Zustand, Jotai, Context. An agent skill from emanueleielo/deepagents-open-lovable.

    111 GitHub stars~1.7k tokensUpdated 4 days ago
    Frontend & DesignAuto-check passed
  • React Expert

    Jeffallan/claude-skills

    Builds React 19 components in TypeScript with Server Components, useActionState forms, custom hooks and state libraries, checked with tsc and React Testing Library.

    12k GitHub stars~1.4k tokensUpdated 5 days ago
    Frontend & DesignAuto-check passed
  • A skill your agent uses when reviewing state management architecture — classifying state types (server/URL/form/UI), checking for over-globalization, Jotai/Zustand/Redux patterns, derived state, and…

    359 GitHub stars~1.4k tokensUpdated 7 days ago
    Frontend & DesignAuto-check passed

More from mobazha/mobazha-unified

All 29 skills in this repo
  • A11y Guide

    mobazha/mobazha-unified

    Accessibility guide for Mobazha following WCAG 2.1 AA standards including color contrast, reduced motion, ARIA patterns, keyboard navigation, focus management, and screen reader testing.

    165 GitHub stars~1.4k tokensUpdated 6 days ago
    Auto-check passed
  • API Reference

    mobazha/mobazha-unified

    Look up Mobazha backend API endpoints, request/response formats, and field mappings.

    165 GitHub stars~1.7k tokensUpdated 6 days ago
    Auto-check passed
  • Code Review

    mobazha/mobazha-unified

    Review code for quality, architecture consistency, and adherence to Mobazha project standards using confidence-based filtering.

    165 GitHub stars~464 tokensUpdated 6 days ago
    Auto-check passed
  • Code Simplifier

    mobazha/mobazha-unified

    Simplify and refine recently written code for clarity, consistency, and maintainability while preserving all functionality.

    165 GitHub stars~601 tokensUpdated 6 days ago
    Auto-check passed
  • Commit Helper

    mobazha/mobazha-unified

    Generate commit messages and run pre-commit validation following Mobazha conventions.

    165 GitHub stars~735 tokensUpdated 6 days ago
    Auto-check passed
  • Component Dev

    mobazha/mobazha-unified

    Create and modify UI components following Mobazha conventions including directory structure, spacing standards, accessibility, and testing.

    165 GitHub stars~638 tokensUpdated 6 days ago
    Auto-check passed

Works with

Questions about State Management

What does State Management do?

Guide for Zustand state management patterns in Mobazha including store design, middleware usage, selectors, persistence, and integration with React Query. State Management is an agent skill from mobazha/mobazha-unified. Guide for Zustand state management patterns in Mobazha including store design, middleware usage, selectors, persistence, and integration with React Query.

When should I use State Management?

State Management fits situations like: modifying stores; working with state management.

How do I install State Management in Claude Code?

Run `npx skills add mobazha/mobazha-unified --skill state-management -a claude-code`. Or copy the skill folder (.cursor/skills/state-management in mobazha/mobazha-unified) into .claude/skills/state-management in your project. Claude Code loads it when a task matches its description.

How do I install State Management in Codex?

Run `npx skills add mobazha/mobazha-unified --skill state-management -a codex`. Or copy the skill folder (.cursor/skills/state-management in mobazha/mobazha-unified) into .agents/skills/state-management in your project. Codex loads it when a task matches its description.

Can I use State Management in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add mobazha/mobazha-unified --skill state-management -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/state-management, .gemini/skills/state-management, .github/skills/state-management and .opencode/skills/state-management in your project.

What does State Management need to run?

SKILL.md names no scripts, command-line tools or credentials: State Management is instructions for the agent only.

Does State Management access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is State Management safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does State Management use?

State Management is published under the MPL-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does State Management use?

About 1.7k tokens (SKILL.md is roughly 6.7k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to State Management?

Skills that share tags, products or a category with State Management: React State Management (involvex/youtube-music-cli, 456 stars), Nextjs15 Init (bear2u/my-skills, 933 stars), Opik Frontend Patterns (comet-ml/opik, 22k stars) and State Management (emanueleielo/deepagents-open-lovable, 111 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains State Management?

mobazha (a GitHub organization) maintains it in mobazha/mobazha-unified, which has 165 GitHub stars. The repository holds 29 skills in this directory. The repository was last updated on October 3, 2026.

Source: mobazha/mobazha-unified on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.