React State Management

作者 wshobson46891e7e60da无许可证收录于 2026年10月8日更新于 2026年10月8日

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.

AI 生成的概览

指导 React 状态管理的选型与模式,涵盖 Redux Toolkit、Zustand、Jotai 和 React Query。

功能
该技能提供现代 React 状态管理的指导,涵盖本地、全局、服务器、URL 和表单状态等类别。它给出在 Redux Toolkit、Zustand、Jotai、React Query 和 SWR 之间进行选择的判断标准,并包含 Zustand 快速上手示例、最佳实践以及从旧版 Redux 迁移到 Redux Toolkit 的示例。它还指向一个参考文件以获取更深入的模式文档。
适用场景
适用于在 React 应用中设置全局状态、在状态管理库之间做选择、管理服务器状态、实现乐观更新、调试状态相关问题,或从旧版 Redux 迁移时。
运行要求
除智能体外无需脚本或软件包;这是仅含说明的技能,附带一个可选的参考文档。

React State Management

Comprehensive guide to modern React state management patterns, from local component state to global stores and server state synchronization.

When to Use This Skill

  • Setting up global state management in a React app
  • Choosing between Redux Toolkit, Zustand, or Jotai
  • Managing server state with React Query or SWR
  • Implementing optimistic updates
  • Debugging state-related issues
  • Migrating from legacy Redux to modern patterns

Core Concepts

1. State Categories

TypeDescriptionSolutions
Local StateComponent-specific, UI stateuseState, useReducer
Global StateShared across componentsRedux Toolkit, Zustand, Jotai
Server StateRemote data, cachingReact Query, SWR, RTK Query
URL StateRoute parameters, searchReact Router, nuqs
Form StateInput values, validationReact Hook Form, Formik

2. Selection Criteria

Small app, simple state → Zustand or JotaiLarge app, complex state → Redux ToolkitHeavy server interaction → React Query + light client stateAtomic/granular updates → Jotai

Quick Start

Zustand (Simplest)

typescript
// store/useStore.tsimport { create } from 'zustand'import { devtools, persist } from 'zustand/middleware'
interface AppState {  user: User | null  theme: 'light' | 'dark'  setUser: (user: User | null) => void  toggleTheme: () => void}
export const useStore = create<AppState>()(  devtools(    persist(      (set) => ({        user: null,        theme: 'light',        setUser: (user) => set({ user }),        toggleTheme: () => set((state) => ({          theme: state.theme === 'light' ? 'dark' : 'light'        })),      }),      { name: 'app-storage' }    )  ))
// Usage in componentfunction Header() {  const { user, theme, toggleTheme } = useStore()  return (    <header className={theme}>      {user?.name}      <button onClick={toggleTheme}>Toggle Theme</button>    </header>  )}

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Best Practices

Do's

  • Colocate state - Keep state as close to where it's used as possible
  • Use selectors - Prevent unnecessary re-renders with selective subscriptions
  • Normalize data - Flatten nested structures for easier updates
  • Type everything - Full TypeScript coverage prevents runtime errors
  • Separate concerns - Server state (React Query) vs client state (Zustand)

Don'ts

  • Don't over-globalize - Not everything needs to be in global state
  • Don't duplicate server state - Let React Query manage it
  • Don't mutate directly - Always use immutable updates
  • Don't store derived data - Compute it instead
  • Don't mix paradigms - Pick one primary solution per category

Migration Guides

From Legacy Redux to RTK

typescript
// Before (legacy Redux)const ADD_TODO = "ADD_TODO";const addTodo = (text) => ({ type: ADD_TODO, payload: text });function todosReducer(state = [], action) {  switch (action.type) {    case ADD_TODO:      return [...state, { text: action.payload, completed: false }];    default:      return state;  }}
// After (Redux Toolkit)const todosSlice = createSlice({  name: "todos",  initialState: [],  reducers: {    addTodo: (state, action: PayloadAction<string>) => {      // Immer allows "mutations"      state.push({ text: action.payload, completed: false });    },  },});

来源与署名

来源:wshobson/agents位于plugins/frontend-mobile-development/skills/react-state-management提交46891e7

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架