[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FBSK87XPWXJCFAP0GGKFRZ":3,"skill-same:01M7FBSK87XPWXJCFAP0GGKFRZ":49},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":27,"commitSha":28,"skillDirectory":29,"forksCount":30,"repositoryHtmlUrl":31,"repositoryHomepageUrl":6,"ownerHtmlUrl":32,"ownerBlogUrl":6,"ownerDescription":33,"updatedAt":34,"install":35,"resources":48},"01M7FBSK87XPWXJCFAP0GGKFRZ","react-state-management",null,"Master modern React state management with Redux Toolkit, Zustand, Jotai, and React Query. Use when setting up global state, managing server state, or choosing between state management solutions.","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Freact-state-management\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: react-state-management\ndescription: \"Master modern React state management with Redux Toolkit, Zustand, Jotai, and React Query. Use when setting up global state, managing server state, or choosing between state management solutions.\"\nrisk: critical\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# React State Management\n\nComprehensive guide to modern React state management patterns, from local component state to global stores and server state synchronization.\n\n## Do not use this skill when\n\n- The task is unrelated to react state management\n- You need a different domain or tool outside this scope\n\n## Instructions\n\n- Clarify goals, constraints, and required inputs.\n- Apply relevant best practices and validate outcomes.\n- Provide actionable steps and verification.\n- If detailed examples are required, open `resources\u002Fimplementation-playbook.md`.\n\n## Use this skill when\n\n- Setting up global state management in a React app\n- Choosing between Redux Toolkit, Zustand, or Jotai\n- Managing server state with React Query or SWR\n- Implementing optimistic updates\n- Debugging state-related issues\n- Migrating from legacy Redux to modern patterns\n\n## Core Concepts\n\n### 1. State Categories\n\n| Type | Description | Solutions |\n|------|-------------|-----------|\n| **Local State** | Component-specific, UI state | useState, useReducer |\n| **Global State** | Shared across components | Redux Toolkit, Zustand, Jotai |\n| **Server State** | Remote data, caching | React Query, SWR, RTK Query |\n| **URL State** | Route parameters, search | React Router, nuqs |\n| **Form State** | Input values, validation | React Hook Form, Formik |\n\n### 2. Selection Criteria\n\n```\nSmall app, simple state → Zustand or Jotai\nLarge app, complex state → Redux Toolkit\nHeavy server interaction → React Query + light client state\nAtomic\u002Fgranular updates → Jotai\n```\n\n## Quick Start\n\n### Zustand (Simplest)\n\n```typescript\n\u002F\u002F store\u002FuseStore.ts\nimport { create } from 'zustand'\nimport { devtools, persist } from 'zustand\u002Fmiddleware'\n\ninterface AppState {\n  user: User | null\n  theme: 'light' | 'dark'\n  setUser: (user: User | null) => void\n  toggleTheme: () => void\n}\n\nexport const useStore = create\u003CAppState>()(\n  devtools(\n    persist(\n      (set) => ({\n        user: null,\n        theme: 'light',\n        setUser: (user) => set({ user }),\n        toggleTheme: () => set((state) => ({\n          theme: state.theme === 'light' ? 'dark' : 'light'\n        })),\n      }),\n      { name: 'app-storage' }\n    )\n  )\n)\n\n\u002F\u002F Usage in component\nfunction Header() {\n  const { user, theme, toggleTheme } = useStore()\n  return (\n    \u003Cheader className={theme}>\n      {user?.name}\n      \u003Cbutton onClick={toggleTheme}>Toggle Theme\u003C\u002Fbutton>\n    \u003C\u002Fheader>\n  )\n}\n```\n\n## Patterns\n\n### Pattern 1: Redux Toolkit with TypeScript\n\n```typescript\n\u002F\u002F store\u002Findex.ts\nimport { configureStore } from '@reduxjs\u002Ftoolkit'\nimport { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport userReducer from '.\u002Fslices\u002FuserSlice'\nimport cartReducer from '.\u002Fslices\u002FcartSlice'\n\nexport const store = configureStore({\n  reducer: {\n    user: userReducer,\n    cart: cartReducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware({\n      serializableCheck: {\n        ignoredActions: ['persist\u002FPERSIST'],\n      },\n    }),\n})\n\nexport type RootState = ReturnType\u003Ctypeof store.getState>\nexport type AppDispatch = typeof store.dispatch\n\n\u002F\u002F Typed hooks\nexport const useAppDispatch: () => AppDispatch = useDispatch\nexport const useAppSelector: TypedUseSelectorHook\u003CRootState> = useSelector\n```\n\n```typescript\n\u002F\u002F store\u002Fslices\u002FuserSlice.ts\nimport { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs\u002Ftoolkit'\n\ninterface User {\n  id: string\n  email: string\n  name: string\n}\n\ninterface UserState {\n  current: User | null\n  status: 'idle' | 'loading' | 'succeeded' | 'failed'\n  error: string | null\n}\n\nconst initialState: UserState = {\n  current: null,\n  status: 'idle',\n  error: null,\n}\n\nexport const fetchUser = createAsyncThunk(\n  'user\u002FfetchUser',\n  async (userId: string, { rejectWithValue }) => {\n    try {\n      const response = await fetch(`\u002Fapi\u002Fusers\u002F${userId}`)\n      if (!response.ok) throw new Error('Failed to fetch user')\n      return await response.json()\n    } catch (error) {\n      return rejectWithValue((error as Error).message)\n    }\n  }\n)\n\nconst userSlice = createSlice({\n  name: 'user',\n  initialState,\n  reducers: {\n    setUser: (state, action: PayloadAction\u003CUser>) => {\n      state.current = action.payload\n      state.status = 'succeeded'\n    },\n    clearUser: (state) => {\n      state.current = null\n      state.status = 'idle'\n    },\n  },\n  extraReducers: (builder) => {\n    builder\n      .addCase(fetchUser.pending, (state) => {\n        state.status = 'loading'\n        state.error = null\n      })\n      .addCase(fetchUser.fulfilled, (state, action) => {\n        state.status = 'succeeded'\n        state.current = action.payload\n      })\n      .addCase(fetchUser.rejected, (state, action) => {\n        state.status = 'failed'\n        state.error = action.payload as string\n      })\n  },\n})\n\nexport const { setUser, clearUser } = userSlice.actions\nexport default userSlice.reducer\n```\n\n### Pattern 2: Zustand with Slices (Scalable)\n\n```typescript\n\u002F\u002F store\u002Fslices\u002FcreateUserSlice.ts\nimport { StateCreator } from 'zustand'\n\nexport interface UserSlice {\n  user: User | null\n  isAuthenticated: boolean\n  login: (credentials: Credentials) => Promise\u003Cvoid>\n  logout: () => void\n}\n\nexport const createUserSlice: StateCreator\u003C\n  UserSlice & CartSlice, \u002F\u002F Combined store type\n  [],\n  [],\n  UserSlice\n> = (set, get) => ({\n  user: null,\n  isAuthenticated: false,\n  login: async (credentials) => {\n    const user = await authApi.login(credentials)\n    set({ user, isAuthenticated: true })\n  },\n  logout: () => {\n    set({ user: null, isAuthenticated: false })\n    \u002F\u002F Can access other slices\n    \u002F\u002F get().clearCart()\n  },\n})\n\n\u002F\u002F store\u002Findex.ts\nimport { create } from 'zustand'\nimport { createUserSlice, UserSlice } from '.\u002Fslices\u002FcreateUserSlice'\nimport { createCartSlice, CartSlice } from '.\u002Fslices\u002FcreateCartSlice'\n\ntype StoreState = UserSlice & CartSlice\n\nexport const useStore = create\u003CStoreState>()((...args) => ({\n  ...createUserSlice(...args),\n  ...createCartSlice(...args),\n}))\n\n\u002F\u002F Selective subscriptions (prevents unnecessary re-renders)\nexport const useUser = () => useStore((state) => state.user)\nexport const useCart = () => useStore((state) => state.cart)\n```\n\n### Pattern 3: Jotai for Atomic State\n\n```typescript\n\u002F\u002F atoms\u002FuserAtoms.ts\nimport { atom } from 'jotai'\nimport { atomWithStorage } from 'jotai\u002Futils'\n\n\u002F\u002F Basic atom\nexport const userAtom = atom\u003CUser | null>(null)\n\n\u002F\u002F Derived atom (computed)\nexport const isAuthenticatedAtom = atom((get) => get(userAtom) !== null)\n\n\u002F\u002F Atom with localStorage persistence\nexport const themeAtom = atomWithStorage\u003C'light' | 'dark'>('theme', 'light')\n\n\u002F\u002F Async atom\nexport const userProfileAtom = atom(async (get) => {\n  const user = get(userAtom)\n  if (!user) return null\n  const response = await fetch(`\u002Fapi\u002Fusers\u002F${user.id}\u002Fprofile`)\n  return response.json()\n})\n\n\u002F\u002F Write-only atom (action)\nexport const logoutAtom = atom(null, (get, set) => {\n  set(userAtom, null)\n  set(cartAtom, [])\n  localStorage.removeItem('token')\n})\n\n\u002F\u002F Usage\nfunction Profile() {\n  const [user] = useAtom(userAtom)\n  const [, logout] = useAtom(logoutAtom)\n  const [profile] = useAtom(userProfileAtom) \u002F\u002F Suspense-enabled\n\n  return (\n    \u003CSuspense fallback={\u003CSkeleton \u002F>}>\n      \u003CProfileContent profile={profile} onLogout={logout} \u002F>\n    \u003C\u002FSuspense>\n  )\n}\n```\n\n### Pattern 4: React Query for Server State\n\n```typescript\n\u002F\u002F hooks\u002FuseUsers.ts\nimport { useQuery, useMutation, useQueryClient } from '@tanstack\u002Freact-query'\n\n\u002F\u002F Query keys factory\nexport const userKeys = {\n  all: ['users'] as const,\n  lists: () => [...userKeys.all, 'list'] as const,\n  list: (filters: UserFilters) => [...userKeys.lists(), filters] as const,\n  details: () => [...userKeys.all, 'detail'] as const,\n  detail: (id: string) => [...userKeys.details(), id] as const,\n}\n\n\u002F\u002F Fetch hook\nexport function useUsers(filters: UserFilters) {\n  return useQuery({\n    queryKey: userKeys.list(filters),\n    queryFn: () => fetchUsers(filters),\n    staleTime: 5 * 60 * 1000, \u002F\u002F 5 minutes\n    gcTime: 30 * 60 * 1000, \u002F\u002F 30 minutes (formerly cacheTime)\n  })\n}\n\n\u002F\u002F Single user hook\nexport function useUser(id: string) {\n  return useQuery({\n    queryKey: userKeys.detail(id),\n    queryFn: () => fetchUser(id),\n    enabled: !!id, \u002F\u002F Don't fetch if no id\n  })\n}\n\n\u002F\u002F Mutation with optimistic update\nexport function useUpdateUser() {\n  const queryClient = useQueryClient()\n\n  return useMutation({\n    mutationFn: updateUser,\n    onMutate: async (newUser) => {\n      \u002F\u002F Cancel outgoing refetches\n      await queryClient.cancelQueries({ queryKey: userKeys.detail(newUser.id) })\n\n      \u002F\u002F Snapshot previous value\n      const previousUser = queryClient.getQueryData(userKeys.detail(newUser.id))\n\n      \u002F\u002F Optimistically update\n      queryClient.setQueryData(userKeys.detail(newUser.id), newUser)\n\n      return { previousUser }\n    },\n    onError: (err, newUser, context) => {\n      \u002F\u002F Rollback on error\n      queryClient.setQueryData(\n        userKeys.detail(newUser.id),\n        context?.previousUser\n      )\n    },\n    onSettled: (data, error, variables) => {\n      \u002F\u002F Refetch after mutation\n      queryClient.invalidateQueries({ queryKey: userKeys.detail(variables.id) })\n    },\n  })\n}\n```\n\n### Pattern 5: Combining Client + Server State\n\n```typescript\n\u002F\u002F Zustand for client state\nconst useUIStore = create\u003CUIState>((set) => ({\n  sidebarOpen: true,\n  modal: null,\n  toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),\n  openModal: (modal) => set({ modal }),\n  closeModal: () => set({ modal: null }),\n}))\n\n\u002F\u002F React Query for server state\nfunction Dashboard() {\n  const { sidebarOpen, toggleSidebar } = useUIStore()\n  const { data: users, isLoading } = useUsers({ active: true })\n  const { data: stats } = useStats()\n\n  if (isLoading) return \u003CDashboardSkeleton \u002F>\n\n  return (\n    \u003Cdiv className={sidebarOpen ? 'with-sidebar' : ''}>\n      \u003CSidebar open={sidebarOpen} onToggle={toggleSidebar} \u002F>\n      \u003Cmain>\n        \u003CStatsCards stats={stats} \u002F>\n        \u003CUserTable users={users} \u002F>\n      \u003C\u002Fmain>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n## Best Practices\n\n### Do's\n- **Colocate state** - Keep state as close to where it's used as possible\n- **Use selectors** - Prevent unnecessary re-renders with selective subscriptions\n- **Normalize data** - Flatten nested structures for easier updates\n- **Type everything** - Full TypeScript coverage prevents runtime errors\n- **Separate concerns** - Server state (React Query) vs client state (Zustand)\n\n### Don'ts\n- **Don't over-globalize** - Not everything needs to be in global state\n- **Don't duplicate server state** - Let React Query manage it\n- **Don't mutate directly** - Always use immutable updates\n- **Don't store derived data** - Compute it instead\n- **Don't mix paradigms** - Pick one primary solution per category\n\n## Migration Guides\n\n### From Legacy Redux to RTK\n\n```typescript\n\u002F\u002F Before (legacy Redux)\nconst ADD_TODO = 'ADD_TODO'\nconst addTodo = (text) => ({ type: ADD_TODO, payload: text })\nfunction todosReducer(state = [], action) {\n  switch (action.type) {\n    case ADD_TODO:\n      return [...state, { text: action.payload, completed: false }]\n    default:\n      return state\n  }\n}\n\n\u002F\u002F After (Redux Toolkit)\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [],\n  reducers: {\n    addTodo: (state, action: PayloadAction\u003Cstring>) => {\n      \u002F\u002F Immer allows \"mutations\"\n      state.push({ text: action.payload, completed: false })\n    },\n  },\n})\n```\n\n## Resources\n\n- [Redux Toolkit Documentation](https:\u002F\u002Fredux-toolkit.js.org\u002F)\n- [Zustand GitHub](https:\u002F\u002Fgithub.com\u002Fpmndrs\u002Fzustand)\n- [Jotai Documentation](https:\u002F\u002Fjotai.org\u002F)\n- [TanStack Query](https:\u002F\u002Ftanstack.com\u002Fquery)\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","# React State Management\n\nComprehensive guide to modern React state management patterns, from local component state to global stores and server state synchronization.\n\n## Do not use this skill when\n\n- The task is unrelated to react state management\n- You need a different domain or tool outside this scope\n\n## Instructions\n\n- Clarify goals, constraints, and required inputs.\n- Apply relevant best practices and validate outcomes.\n- Provide actionable steps and verification.\n- If detailed examples are required, open `resources\u002Fimplementation-playbook.md`.\n\n## Use this skill when\n\n- Setting up global state management in a React app\n- Choosing between Redux Toolkit, Zustand, or Jotai\n- Managing server state with React Query or SWR\n- Implementing optimistic updates\n- Debugging state-related issues\n- Migrating from legacy Redux to modern patterns\n\n## Core Concepts\n\n### 1. State Categories\n\n| Type | Description | Solutions |\n|------|-------------|-----------|\n| **Local State** | Component-specific, UI state | useState, useReducer |\n| **Global State** | Shared across components | Redux Toolkit, Zustand, Jotai |\n| **Server State** | Remote data, caching | React Query, SWR, RTK Query |\n| **URL State** | Route parameters, search | React Router, nuqs |\n| **Form State** | Input values, validation | React Hook Form, Formik |\n\n### 2. Selection Criteria\n\n```\nSmall app, simple state → Zustand or Jotai\nLarge app, complex state → Redux Toolkit\nHeavy server interaction → React Query + light client state\nAtomic\u002Fgranular updates → Jotai\n```\n\n## Quick Start\n\n### Zustand (Simplest)\n\n```typescript\n\u002F\u002F store\u002FuseStore.ts\nimport { create } from 'zustand'\nimport { devtools, persist } from 'zustand\u002Fmiddleware'\n\ninterface AppState {\n  user: User | null\n  theme: 'light' | 'dark'\n  setUser: (user: User | null) => void\n  toggleTheme: () => void\n}\n\nexport const useStore = create\u003CAppState>()(\n  devtools(\n    persist(\n      (set) => ({\n        user: null,\n        theme: 'light',\n        setUser: (user) => set({ user }),\n        toggleTheme: () => set((state) => ({\n          theme: state.theme === 'light' ? 'dark' : 'light'\n        })),\n      }),\n      { name: 'app-storage' }\n    )\n  )\n)\n\n\u002F\u002F Usage in component\nfunction Header() {\n  const { user, theme, toggleTheme } = useStore()\n  return (\n    \u003Cheader className={theme}>\n      {user?.name}\n      \u003Cbutton onClick={toggleTheme}>Toggle Theme\u003C\u002Fbutton>\n    \u003C\u002Fheader>\n  )\n}\n```\n\n## Patterns\n\n### Pattern 1: Redux Toolkit with TypeScript\n\n```typescript\n\u002F\u002F store\u002Findex.ts\nimport { configureStore } from '@reduxjs\u002Ftoolkit'\nimport { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport userReducer from '.\u002Fslices\u002FuserSlice'\nimport cartReducer from '.\u002Fslices\u002FcartSlice'\n\nexport const store = configureStore({\n  reducer: {\n    user: userReducer,\n    cart: cartReducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware({\n      serializableCheck: {\n        ignoredActions: ['persist\u002FPERSIST'],\n      },\n    }),\n})\n\nexport type RootState = ReturnType\u003Ctypeof store.getState>\nexport type AppDispatch = typeof store.dispatch\n\n\u002F\u002F Typed hooks\nexport const useAppDispatch: () => AppDispatch = useDispatch\nexport const useAppSelector: TypedUseSelectorHook\u003CRootState> = useSelector\n```\n\n```typescript\n\u002F\u002F store\u002Fslices\u002FuserSlice.ts\nimport { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs\u002Ftoolkit'\n\ninterface User {\n  id: string\n  email: string\n  name: string\n}\n\ninterface UserState {\n  current: User | null\n  status: 'idle' | 'loading' | 'succeeded' | 'failed'\n  error: string | null\n}\n\nconst initialState: UserState = {\n  current: null,\n  status: 'idle',\n  error: null,\n}\n\nexport const fetchUser = createAsyncThunk(\n  'user\u002FfetchUser',\n  async (userId: string, { rejectWithValue }) => {\n    try {\n      const response = await fetch(`\u002Fapi\u002Fusers\u002F${userId}`)\n      if (!response.ok) throw new Error('Failed to fetch user')\n      return await response.json()\n    } catch (error) {\n      return rejectWithValue((error as Error).message)\n    }\n  }\n)\n\nconst userSlice = createSlice({\n  name: 'user',\n  initialState,\n  reducers: {\n    setUser: (state, action: PayloadAction\u003CUser>) => {\n      state.current = action.payload\n      state.status = 'succeeded'\n    },\n    clearUser: (state) => {\n      state.current = null\n      state.status = 'idle'\n    },\n  },\n  extraReducers: (builder) => {\n    builder\n      .addCase(fetchUser.pending, (state) => {\n        state.status = 'loading'\n        state.error = null\n      })\n      .addCase(fetchUser.fulfilled, (state, action) => {\n        state.status = 'succeeded'\n        state.current = action.payload\n      })\n      .addCase(fetchUser.rejected, (state, action) => {\n        state.status = 'failed'\n        state.error = action.payload as string\n      })\n  },\n})\n\nexport const { setUser, clearUser } = userSlice.actions\nexport default userSlice.reducer\n```\n\n### Pattern 2: Zustand with Slices (Scalable)\n\n```typescript\n\u002F\u002F store\u002Fslices\u002FcreateUserSlice.ts\nimport { StateCreator } from 'zustand'\n\nexport interface UserSlice {\n  user: User | null\n  isAuthenticated: boolean\n  login: (credentials: Credentials) => Promise\u003Cvoid>\n  logout: () => void\n}\n\nexport const createUserSlice: StateCreator\u003C\n  UserSlice & CartSlice, \u002F\u002F Combined store type\n  [],\n  [],\n  UserSlice\n> = (set, get) => ({\n  user: null,\n  isAuthenticated: false,\n  login: async (credentials) => {\n    const user = await authApi.login(credentials)\n    set({ user, isAuthenticated: true })\n  },\n  logout: () => {\n    set({ user: null, isAuthenticated: false })\n    \u002F\u002F Can access other slices\n    \u002F\u002F get().clearCart()\n  },\n})\n\n\u002F\u002F store\u002Findex.ts\nimport { create } from 'zustand'\nimport { createUserSlice, UserSlice } from '.\u002Fslices\u002FcreateUserSlice'\nimport { createCartSlice, CartSlice } from '.\u002Fslices\u002FcreateCartSlice'\n\ntype StoreState = UserSlice & CartSlice\n\nexport const useStore = create\u003CStoreState>()((...args) => ({\n  ...createUserSlice(...args),\n  ...createCartSlice(...args),\n}))\n\n\u002F\u002F Selective subscriptions (prevents unnecessary re-renders)\nexport const useUser = () => useStore((state) => state.user)\nexport const useCart = () => useStore((state) => state.cart)\n```\n\n### Pattern 3: Jotai for Atomic State\n\n```typescript\n\u002F\u002F atoms\u002FuserAtoms.ts\nimport { atom } from 'jotai'\nimport { atomWithStorage } from 'jotai\u002Futils'\n\n\u002F\u002F Basic atom\nexport const userAtom = atom\u003CUser | null>(null)\n\n\u002F\u002F Derived atom (computed)\nexport const isAuthenticatedAtom = atom((get) => get(userAtom) !== null)\n\n\u002F\u002F Atom with localStorage persistence\nexport const themeAtom = atomWithStorage\u003C'light' | 'dark'>('theme', 'light')\n\n\u002F\u002F Async atom\nexport const userProfileAtom = atom(async (get) => {\n  const user = get(userAtom)\n  if (!user) return null\n  const response = await fetch(`\u002Fapi\u002Fusers\u002F${user.id}\u002Fprofile`)\n  return response.json()\n})\n\n\u002F\u002F Write-only atom (action)\nexport const logoutAtom = atom(null, (get, set) => {\n  set(userAtom, null)\n  set(cartAtom, [])\n  localStorage.removeItem('token')\n})\n\n\u002F\u002F Usage\nfunction Profile() {\n  const [user] = useAtom(userAtom)\n  const [, logout] = useAtom(logoutAtom)\n  const [profile] = useAtom(userProfileAtom) \u002F\u002F Suspense-enabled\n\n  return (\n    \u003CSuspense fallback={\u003CSkeleton \u002F>}>\n      \u003CProfileContent profile={profile} onLogout={logout} \u002F>\n    \u003C\u002FSuspense>\n  )\n}\n```\n\n### Pattern 4: React Query for Server State\n\n```typescript\n\u002F\u002F hooks\u002FuseUsers.ts\nimport { useQuery, useMutation, useQueryClient } from '@tanstack\u002Freact-query'\n\n\u002F\u002F Query keys factory\nexport const userKeys = {\n  all: ['users'] as const,\n  lists: () => [...userKeys.all, 'list'] as const,\n  list: (filters: UserFilters) => [...userKeys.lists(), filters] as const,\n  details: () => [...userKeys.all, 'detail'] as const,\n  detail: (id: string) => [...userKeys.details(), id] as const,\n}\n\n\u002F\u002F Fetch hook\nexport function useUsers(filters: UserFilters) {\n  return useQuery({\n    queryKey: userKeys.list(filters),\n    queryFn: () => fetchUsers(filters),\n    staleTime: 5 * 60 * 1000, \u002F\u002F 5 minutes\n    gcTime: 30 * 60 * 1000, \u002F\u002F 30 minutes (formerly cacheTime)\n  })\n}\n\n\u002F\u002F Single user hook\nexport function useUser(id: string) {\n  return useQuery({\n    queryKey: userKeys.detail(id),\n    queryFn: () => fetchUser(id),\n    enabled: !!id, \u002F\u002F Don't fetch if no id\n  })\n}\n\n\u002F\u002F Mutation with optimistic update\nexport function useUpdateUser() {\n  const queryClient = useQueryClient()\n\n  return useMutation({\n    mutationFn: updateUser,\n    onMutate: async (newUser) => {\n      \u002F\u002F Cancel outgoing refetches\n      await queryClient.cancelQueries({ queryKey: userKeys.detail(newUser.id) })\n\n      \u002F\u002F Snapshot previous value\n      const previousUser = queryClient.getQueryData(userKeys.detail(newUser.id))\n\n      \u002F\u002F Optimistically update\n      queryClient.setQueryData(userKeys.detail(newUser.id), newUser)\n\n      return { previousUser }\n    },\n    onError: (err, newUser, context) => {\n      \u002F\u002F Rollback on error\n      queryClient.setQueryData(\n        userKeys.detail(newUser.id),\n        context?.previousUser\n      )\n    },\n    onSettled: (data, error, variables) => {\n      \u002F\u002F Refetch after mutation\n      queryClient.invalidateQueries({ queryKey: userKeys.detail(variables.id) })\n    },\n  })\n}\n```\n\n### Pattern 5: Combining Client + Server State\n\n```typescript\n\u002F\u002F Zustand for client state\nconst useUIStore = create\u003CUIState>((set) => ({\n  sidebarOpen: true,\n  modal: null,\n  toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })),\n  openModal: (modal) => set({ modal }),\n  closeModal: () => set({ modal: null }),\n}))\n\n\u002F\u002F React Query for server state\nfunction Dashboard() {\n  const { sidebarOpen, toggleSidebar } = useUIStore()\n  const { data: users, isLoading } = useUsers({ active: true })\n  const { data: stats } = useStats()\n\n  if (isLoading) return \u003CDashboardSkeleton \u002F>\n\n  return (\n    \u003Cdiv className={sidebarOpen ? 'with-sidebar' : ''}>\n      \u003CSidebar open={sidebarOpen} onToggle={toggleSidebar} \u002F>\n      \u003Cmain>\n        \u003CStatsCards stats={stats} \u002F>\n        \u003CUserTable users={users} \u002F>\n      \u003C\u002Fmain>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n## Best Practices\n\n### Do's\n- **Colocate state** - Keep state as close to where it's used as possible\n- **Use selectors** - Prevent unnecessary re-renders with selective subscriptions\n- **Normalize data** - Flatten nested structures for easier updates\n- **Type everything** - Full TypeScript coverage prevents runtime errors\n- **Separate concerns** - Server state (React Query) vs client state (Zustand)\n\n### Don'ts\n- **Don't over-globalize** - Not everything needs to be in global state\n- **Don't duplicate server state** - Let React Query manage it\n- **Don't mutate directly** - Always use immutable updates\n- **Don't store derived data** - Compute it instead\n- **Don't mix paradigms** - Pick one primary solution per category\n\n## Migration Guides\n\n### From Legacy Redux to RTK\n\n```typescript\n\u002F\u002F Before (legacy Redux)\nconst ADD_TODO = 'ADD_TODO'\nconst addTodo = (text) => ({ type: ADD_TODO, payload: text })\nfunction todosReducer(state = [], action) {\n  switch (action.type) {\n    case ADD_TODO:\n      return [...state, { text: action.payload, completed: false }]\n    default:\n      return state\n  }\n}\n\n\u002F\u002F After (Redux Toolkit)\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [],\n  reducers: {\n    addTodo: (state, action: PayloadAction\u003Cstring>) => {\n      \u002F\u002F Immer allows \"mutations\"\n      state.push({ text: action.payload, completed: false })\n    },\n  },\n})\n```\n\n## Resources\n\n- [Redux Toolkit Documentation](https:\u002F\u002Fredux-toolkit.js.org\u002F)\n- [Zustand GitHub](https:\u002F\u002Fgithub.com\u002Fpmndrs\u002Fzustand)\n- [Jotai Documentation](https:\u002F\u002Fjotai.org\u002F)\n- [TanStack Query](https:\u002F\u002Ftanstack.com\u002Fquery)\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n",{"name":5,"risk":24,"source":25,"date_added":26,"description":7},"critical","community","2026-02-27","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","06-前端与设计\u002Freact-state-management",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill react-state-management",{"tool":41,"command":42},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill react-state-management",{"tool":44,"command":45},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill react-state-management","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Freact-state-management\u002FSKILL.md",true,[],[50,57,62,69,76,83],{"skillNo":51,"name":52,"nameZh":6,"description":53,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":58,"name":52,"nameZh":6,"description":53,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]