Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问clear审计通过

state-management状态管理

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

2,694

周安装

109

GitHub Stars

33

下载量

846
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:state-management(状态管理)
来源仓库:https://github.com/asyrafhussin/agent-skills
仓库路径:skills/state-management
安装命令:
npx skills add https://github.com/asyrafhussin/agent-skills --skill state-management
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/asyrafhussin/agent-skills --skill state-management

简介

用于辅助前端页面、组件和样式开发,支持 React、Next.js、Vue 等技术栈的状态逻辑设计与性能优化。

  • 它基于 TanStack Query v5 和 Zustand v5 提供类型安全的状态管理模式,包含缓存策略、数据预取和副作用处理方案。
  • 使用时需结合项目现有设计系统与路由结构,避免生成孤立代码片段;涉及页面改动时应配合本地预览验证效果。
  • 输出示例均经 v5 API 验证,但不保证与旧版本完全兼容,建议在测试环境先行验证。
  • state-management 属于前端设计类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

State Management with React Query + Zustand

Version 1.1.0 | TanStack Query v5 | Zustand v5 | March 2026

Note: This document provides comprehensive patterns for AI agents and LLMs working with TanStack Query v5 and Zustand v5. All examples are verified against v5 APIs. Optimized for automated refactoring, code generation, and state management best practices.

v5 Breaking Changes (Quick Reference)

TanStack Query v5:

  • cacheTimegcTime
  • keepPreviousData option → placeholderData: keepPreviousData (imported helper)
  • isPreviousDataisPlaceholderData
  • onSuccess/onError/onSettled removed from useQuery — still valid on useMutation
  • suspense: true on useQuery removed → use useSuspenseQuery

Zustand v5:

  • shallow as 2nd arg removed → useShallow from zustand/shallow
  • Selectors returning new references need useShallow to avoid infinite loops

Security: Persist Middleware

Never persist auth tokens, passwords, or secrets to localStorage/sessionStorage. Use partialize to persist only non-sensitive state. Manage tokens via HttpOnly cookies.

Comprehensive patterns for server state (React Query) and client state (Zustand). Contains 26+ rules for efficient data fetching and state management.

When to Apply

Reference these guidelines when:

  • Fetching data from APIs
  • Managing server state and caching
  • Handling mutations and optimistic updates
  • Creating client-side stores
  • Combining React Query with Zustand

Rule Categories by Priority

PriorityCategoryImpactPrefix
1React Query BasicsCRITICALrq-
2Zustand Store PatternsCRITICALzs-
3Caching & InvalidationHIGHcache-
4Mutations & UpdatesHIGHmut-
5Optimistic UpdatesMEDIUMopt-
6DevTools & DebuggingMEDIUMdev-
7Advanced PatternsLOWadv-

Quick Reference

1. React Query Basics (CRITICAL)

  • rq-setup - QueryClient and Provider setup
  • rq-usequery - Basic useQuery patterns
  • rq-querykeys - Query key organization
  • rq-loading-error - Handle loading and error states
  • rq-enabled - Conditional queries

2. Zustand Store Patterns (CRITICAL)

  • zs-create-store - Create basic store
  • zs-typescript - TypeScript store patterns
  • zs-selectors - Efficient selectors
  • zs-actions - Action patterns
  • zs-persist - Persist state to storage

3. Caching & Invalidation (HIGH)

  • cache-stale-time - Configure stale time
  • cache-gc-time - Configure garbage collection
  • cache-invalidation - Invalidate queries
  • cache-prefetch - Prefetch data
  • cache-initial-data - Set initial data

4. Mutations & Updates (HIGH)

  • mut-usemutation - Basic useMutation
  • mut-callbacks - onSuccess, onError callbacks
  • mut-invalidate - Invalidate after mutation
  • mut-update-cache - Direct cache updates

5. Optimistic Updates (MEDIUM)

  • opt-basic - Basic optimistic updates
  • opt-rollback - Rollback on error
  • opt-variables - Use mutation variables

6. DevTools & Debugging (MEDIUM)

  • dev-react-query - React Query DevTools
  • dev-zustand - Zustand DevTools
  • dev-debugging - Debug strategies

7. Advanced Patterns (LOW)

  • adv-infinite-queries - Infinite scrolling
  • adv-parallel-queries - Parallel requests
  • adv-dependent-queries - Dependent queries
  • adv-query-zustand - Combine RQ with Zustand

React Query Patterns

Setup

// lib/queryClient.ts
import { QueryClient } from '@tanstack/react-query'

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
      gcTime: 1000 * 60 * 30,   // 30 minutes (formerly cacheTime)
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
})

// App.tsx
import { QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { queryClient } from './lib/queryClient'

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Router />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}

Query Keys Factory

// lib/queryKeys.ts
export const queryKeys = {
  // All posts
  posts: {
    all: ['posts'] as const,
    lists: () => [...queryKeys.posts.all, 'list'] as const,
    list: (filters: PostFilters) =>
      [...queryKeys.posts.lists(), filters] as const,
    details: () => [...queryKeys.posts.all, 'detail'] as const,
    detail: (id: number) => [...queryKeys.posts.details(), id] as const,
  },

  // All users
  users: {
    all: ['users'] as const,
    detail: (id: number) => [...queryKeys.users.all, id] as const,
    posts: (userId: number) => [...queryKeys.users.all, userId, 'posts'] as const,
  },
}

useQuery Hook

// hooks/usePosts.ts
import { useQuery } from '@tanstack/react-query'
import { queryKeys } from '@/lib/queryKeys'
import { fetchPosts, fetchPost } from '@/api/posts'

export function usePosts(filters?: PostFilters) {
  return useQuery({
    queryKey: queryKeys.posts.list(filters ?? {}),
    queryFn: () => fetchPosts(filters),
  })
}

export function usePost(id: number) {
  return useQuery({
    queryKey: queryKeys.posts.detail(id),
    queryFn: () => fetchPost(id),
    enabled: !!id, // Only run if id exists
  })
}

// Usage in component
function PostList() {
  const { data: posts, isLoading, error } = usePosts()

  if (isLoading) return <Spinner />
  if (error) return <Error message={error.message} />

  return (
    <ul>
      {posts?.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

useMutation Hook

// hooks/useCreatePost.ts
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { queryKeys } from '@/lib/queryKeys'
import { createPost } from '@/api/posts'

export function useCreatePost() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: createPost,
    onSuccess: (newPost) => {
      // Invalidate and refetch posts list
      queryClient.invalidateQueries({
        queryKey: queryKeys.posts.lists(),
      })
    },
    onError: (error) => {
      console.error('Failed to create post:', error)
    },
  })
}

// Usage
function CreatePostForm() {
  const { mutate, isPending } = useCreatePost()

  const handleSubmit = (data: CreatePostData) => {
    mutate(data)
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
      <button disabled={isPending}>
        {isPending ? 'Creating...' : 'Create'}
      </button>
    </form>
  )
}

Optimistic Updates

export function useUpdatePost() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: updatePost,
    onMutate: async (updatedPost) => {
      // Cancel outgoing refetches
      await queryClient.cancelQueries({
        queryKey: queryKeys.posts.detail(updatedPost.id),
      })

      // Snapshot previous value
      const previousPost = queryClient.getQueryData(
        queryKeys.posts.detail(updatedPost.id)
      )

      // Optimistically update
      queryClient.setQueryData(
        queryKeys.posts.detail(updatedPost.id),
        updatedPost
      )

      return { previousPost }
    },
    onError: (err, updatedPost, context) => {
      // Rollback on error
      queryClient.setQueryData(
        queryKeys.posts.detail(updatedPost.id),
        context?.previousPost
      )
    },
    onSettled: (data, error, variables) => {
      // Refetch after settle
      queryClient.invalidateQueries({
        queryKey: queryKeys.posts.detail(variables.id),
      })
    },
  })
}

Zustand Patterns

Basic Store

// stores/useCounterStore.ts
import { create } from 'zustand'

interface CounterState {
  count: number
  increment: () => void
  decrement: () => void
  reset: () => void
}

export const useCounterStore = create<CounterState>((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
  reset: () => set({ count: 0 }),
}))

// Usage
function Counter() {
  const { count, increment, decrement } = useCounterStore()

  return (
    <div>
      <span>{count}</span>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  )
}

Store with TypeScript and Middleware

// stores/useAuthStore.ts
import { create } from 'zustand'
import { persist, devtools } from 'zustand/middleware'

interface User {
  id: number
  name: string
  email: string
}

interface AuthState {
  user: User | null
  isAuthenticated: boolean
  login: (user: User) => void
  logout: () => void
}

// ✅ Never persist tokens to localStorage — use HttpOnly cookies server-side
export const useAuthStore = create<AuthState>()(
  devtools(
    persist(
      (set) => ({
        user: null,
        isAuthenticated: false,

        login: (user) =>
          set({
            user,
            isAuthenticated: true,
          }),

        logout: () =>
          set({
            user: null,
            isAuthenticated: false,
          }),
      }),
      {
        name: 'auth-storage',
        // Only persist display info and auth flag — tokens must NOT be included
        partialize: (state) => ({
          user: state.user,
          isAuthenticated: state.isAuthenticated,
        }),
      }
    )
  )
)

Selectors for Performance

// Use selectors to prevent unnecessary re-renders
function UserName() {
  // Only re-renders when user.name changes
  const name = useAuthStore((state) => state.user?.name)
  return <span>{name}</span>
}

// Multiple selectors
function UserInfo() {
  const user = useAuthStore((state) => state.user)
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)

  if (!isAuthenticated) return <LoginButton />
  return <span>{user?.name}</span>
}

Combining React Query + Zustand

// Server state: React Query (what comes from API)
const { data: posts } = usePosts()

// Client state: Zustand (UI state)
const { selectedPostId, selectPost } = useUIStore()

// Use together
const selectedPost = posts?.find((p) => p.id === selectedPostId)

How to Use

Read individual rule files for detailed explanations and code examples:

rules/rq-usequery.md
rules/rq-query-keys.md
rules/rq-mutation-setup.md
rules/rq-optimistic-updates.md
rules/zs-create-store.md
rules/zs-persist.md
rules/rq-query-invalidation.md
rules/rq-prefetching.md

References

React Query (TanStack Query)

  1. TanStack Query Documentation
  2. React Query Overview
  3. Queries Guide
  4. Mutations Guide
  5. Query Keys Guide
  6. Optimistic Updates
  7. Infinite Queries
  8. Paginated Queries
  9. React Query DevTools

Zustand

  1. Zustand Demo
  2. Zustand GitHub
  3. Getting Started
  4. TypeScript Guide
  5. Persisting Store Data
  6. Zustand Recipes

License

This skill is provided as-is for educational and development purposes. React Query is MIT licensed by TanStack. Zustand is MIT licensed by Poimandres (pmnd.rs).

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

27.69%
按下载量换算234

Antigravity

22.72%
按下载量换算192

Gemini CLI

18.11%
按下载量换算153

windsurf

14.8%
按下载量换算125

Codex

8.26%
按下载量换算70

OpenCode

3.99%
按下载量换算34

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills