Skip to content

状态 Management

选择之间上下文, useReducer, Redux, and Zustand for 全局状态.

你将学到

  • spectrum 的状态 management 解答
  • 当局部状态, 上下文, or 库是 appropriate
  • Redux Toolkit for 复杂 applications
  • Zustand for lightweight 全局状态

概念讲解

The State Management Spectrum

State management in React ranges from simple to complex. Local component state (useState) handles state that only one component needs. Lifted state (state in a common parent) handles state shared by a few siblings. Context handles low-frequency global state like theme and auth. useReducer with Context handles medium-complexity global state. Dedicated libraries (Redux, Zustand, Jotai, Recoil) handle complex, high-frequency, or deeply interconnected state. The key is to use the simplest solution that works — do not reach for Redux on day one.

When to Use What

Use useState for independent local state. Use lifted state when 2-3 sibling components need to share state. Use Context for app-wide, low-frequency values (theme, locale, current user, auth status). Use useReducer + Context when you have complex state transitions that need to be centralized and testable. Use a dedicated library when you have high-frequency updates that would cause too many re-renders with Context, when you need time-travel debugging, or when state is deeply interconnected across many components.

Redux Toolkit

Redux Toolkit (RTK) is the modern, recommended way to use Redux. It dramatically reduces boilerplate with createSlice (which auto-generates action creators and reducers), configureStore (which sets up the store with sensible defaults), and createAsyncThunk for async logic. RTK Query (included in RTK) handles data fetching and caching, replacing the need for a separate data library. Use Redux when you have complex state logic, need middleware, or want the Redux DevTools for time-travel debugging.

Zustand

Zustand is a lightweight state management library that is increasingly popular as a Redux alternative. You create a store with a hook function, and components subscribe to slices of the store. It has minimal boilerplate, supports middleware (persist, devtools), and does not wrap your app in a provider. Zustand is ideal for medium to large apps that need global state without Redux's ceremony. Its selective subscription model also avoids the re-render problems of Context.

示例代码

              // Zustand — lightweight global state with minimal boilerplate.
import { create } from "zustand";

interface BearStore {
  bears: number;
  increase: () => void;
  reset: () => void;
}

const useBearStore = create<BearStore>((set) => ({
  bears: 0,
  increase: () => set(state => ({ bears: state.bears + 1 })),
  reset: () => set({ bears: 0 }),
}));

// Components subscribe to only what they need — selective re-renders.
function BearCounter() {
  const bears = useBearStore(state => state.bears);
  return <h1>{bears} bears</h1>;
}

function Controls() {
  const increase = useBearStore(state => state.increase);
  const reset = useBearStore(state => state.reset);
  return (
    <>
      <button onClick={increase}>Add bear</button>
      <button onClick={reset}>Reset</button>
    </>
  );
}

// No provider wrapper needed — just use the hook anywhere.
function App() {
  return <><BearCounter /><Controls /></>;
}
            

Zustand 创建存储使用创建(). 组件 subscribe 到特定 slices, 所以仅 组件 using 更改 slice re-渲染. 否 provider wrapper 是需要.

动手试一试

  • JSON Formatter

    Inspect 存储状态 shapes 当设计你的状态架构.

  • JSON 到 YAML

    Convert 状态 configs 到 YAML for 配置 or documentation.

常见错误

错误写法

Reaching for Redux on 每个项目 regardless 的复杂度

正确做法

开始使用 useState and 上下文. 仅添加 Redux or Zustand 当你 有复杂, 高-frequency, or deeply interconnected 状态那个上下文 cannot handle efficiently. Premature 状态库 添加不必要复杂度.

错误写法

Putting 一切 in 全局状态

正确做法

Keep 状态 as 局部 as 可能. 仅 lift 状态到 常见 parent or 全局存储当 多个组件需要它. Over-globalizing 状态制作组件 harder 到测试 and reason 关于 in isolation.

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误