跳到正文
Skillpedia
网站与界面(前端)41k · #6701

react-state-management

它能做什么

这份指南教你如何在 React 应用中组织和管理数据。内容涵盖从只属于单个组件的数据,到整个应用共享的数据,再到从服务器获取的数据。

适用场景

  • ✓当你需要在 React 应用的不同部分之间共享信息时。
  • ✓当你需要决定用哪个工具来管理从服务器获取的数据时。
  • ✓用于整理整个应用都会用到的数据。

技能链接

https://github.com/wshobson/agents/blob/main/plugins/frontend-mobile-development/skills/react-state-management/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/wshobson/agents/blob/main/plugins/frontend-mobile-development/skills/react-state-management/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“我该如何整理 React 应用从服务器获取的数据?”

每周 5 个新技能,1 分钟读完。

工作原理

这份指南会讲解不同类型的数据(本地、全局、服务器数据),并针对每种情况推荐 Redux Toolkit、Zustand、Jotai 和 React Query 等工具。此外,还提供了这些工具的使用示例。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

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

Type Description Solutions
Local State Component-specific, UI state useState, useReducer
Global State Shared across components Redux Toolkit, Zustand, Jotai
Server State Remote data, caching React Query, SWR, RTK Query
URL State Route parameters, search React Router, nuqs
Form State Input values, validation React Hook Form, Formik

2. Selection Criteria

Small app, simple state → Zustand or Jotai
Large app, complex state → Redux Toolkit
Heavy server interaction → React Query + light client state
Atomic/granular updates → Jotai

Quick Start

Zustand (Simplest)

// store/useStore.ts
import { 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 component
function 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

// 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 });
    },
  },
});
常见问题

本地状态和全局状态有什么区别?

本地状态是只供单个组件使用的信息。全局状态则是需要被应用中不同部分的多个组件访问的信息。

什么时候应该使用 React Query?

当你需要获取、缓存并同步来自服务器的数据时,React Query 最为合适。

哪个工具最简单,适合入门?

在 React 应用中管理全局状态时,Zustand 常被推荐为更简单的选择。

详情

作者的原始描述

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.

repo: wshobson/agents

热度

GitHub 星标
41k
排名
#6701
许可证
MIT
更新时间
2026/10/15

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能