jotai、mobx-react、mobx-react-lite、react-query、react-redux、recoil、redux 和 zustand 都是用于 React 应用中管理状态或处理异步数据的主流库,但它们在设计哲学、使用方式和适用场景上存在显著差异。redux 和 react-redux 提供了基于单向数据流和不可变状态的全局状态管理方案;mobx-react 和 mobx-react-lite 基于响应式编程模型,通过可观察对象自动追踪依赖;recoil 和 jotai 采用原子化(atom-based)状态模型,支持细粒度更新和派生状态;zustand 则以简洁的 API 提供轻量级全局状态管理;而 react-query 专注于服务端状态(如 API 数据)的获取、缓存和同步,并不直接管理客户端 UI 状态。这些库共同构成了现代 React 应用状态管理的完整工具链。
在现代 React 开发中,状态管理远不止 useState 和 useReducer。面对全局状态、服务端数据同步、性能优化等挑战,社区涌现出多种解决方案。本文将深入对比 jotai、mobx-react、mobx-react-lite、react-query、react-redux、recoil、redux 和 zustand,帮助你在真实项目中做出明智选择。
重要提示:
mobx-react已在官方文档中标记为“仅用于遗留项目”,新项目应使用mobx-react-lite。本文仍包含它以供迁移参考。
不同库对“状态”本身的理解截然不同,这直接影响了代码组织方式。
redux 和 react-redux 基于单一不可变状态树。所有状态变更必须通过纯函数(reducers)处理 action。
// redux + react-redux
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
if (action.type === 'increment') return { count: state.count + 1 };
return state;
};
const store = createStore(reducer);
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return <button onClick={() => dispatch({ type: 'increment' })}>{count}</button>;
}
// App.js
<Provider store={store}>
<Counter />
</Provider>
mobx-react-lite 将状态视为可观察对象,组件自动追踪所用属性并在变化时重渲染。
// mobx-react-lite
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';
class Store {
count = 0;
constructor() { makeAutoObservable(this); }
increment = () => { this.count++; };
}
const store = new Store();
const Counter = observer(() => (
<button onClick={store.increment}>{store.count}</button>
));
recoil 和 jotai 将状态拆分为独立的“原子”(atoms),支持派生状态(selectors)。
// recoil
import { atom, useRecoilState, selector } from 'recoil';
const countAtom = atom({ key: 'count', default: 0 });
const doubledCount = selector({
key: 'doubledCount',
get: ({ get }) => get(countAtom) * 2
});
function Counter() {
const [count, setCount] = useRecoilState(countAtom);
const double = useRecoilValue(doubledCount);
return <div>{count} → {double}</div>;
}
// jotai(无需 Provider)
import { atom, useAtom } from 'jotai';
const countAtom = atom(0);
const doubledCount = atom((get) => get(countAtom) * 2);
function Counter() {
const [count, setCount] = useAtom(countAtom);
const [double] = useAtom(doubledCount);
return <div>{count} → {double}</div>;
}
zustand 提供类似 Redux 的 actions,但允许直接修改状态,且无需 Provider。
// zustand
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 }))
}));
function Counter() {
const { count, increment } = useStore();
return <button onClick={increment}>{count}</button>;
}
react-query 不管理 UI 状态,而是处理异步数据获取、缓存和同步。
// react-query
import { useQuery } from '@tanstack/react-query';
function UserProfile({ userId }) {
const { data, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId)
});
if (isLoading) return <div>Loading...</div>;
return <div>{data.name}</div>;
}
如何处理副作用(如 API 调用)是状态库的关键差异点。
通过 redux-thunk 或 redux-saga 处理异步逻辑。
// redux-thunk
const fetchUser = (id) => async (dispatch) => {
dispatch({ type: 'FETCH_START' });
try {
const user = await api.getUser(id);
dispatch({ type: 'FETCH_SUCCESS', payload: user });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', error });
}
};
// 在组件中
useEffect(() => {
dispatch(fetchUser(123));
}, [dispatch]);
异步逻辑可直接写在 action 中(需启用 runInAction 或使用 makeAutoObservable 的 async 支持)。
// mobx-react-lite
class UserStore {
user = null;
loading = false;
constructor() { makeAutoObservable(this); }
async fetchUser(id) {
this.loading = true;
try {
this.user = await api.getUser(id);
} finally {
this.loading = false;
}
}
}
通过异步 selector 处理数据获取,自动管理加载/错误状态。
// recoil
const userQuery = selector({
key: 'userQuery',
get: async ({ get }) => {
const id = get(userIdAtom);
const response = await fetch(`/api/users/${id}`);
return response.json();
}
});
// jotai
const userAtom = atom(async (get) => {
const id = get(userIdAtom);
const res = await fetch(`/api/users/${id}`);
return res.json();
});
类似 MobX,异步逻辑可内联在 actions 中。
// zustand
const useStore = create((set) => ({
user: null,
loading: false,
fetchUser: async (id) => {
set({ loading: true });
try {
const user = await api.getUser(id);
set({ user, loading: false });
} catch (error) {
set({ loading: false, error });
}
}
}));
内置加载、错误、重试、缓存等机制,无需手动管理状态。
// react-query
const { data, error, isLoading, refetch } = useQuery({
queryKey: ['user', id],
queryFn: () => api.getUser(id),
retry: 3,
staleTime: 5000
});
react-redux、mobx-react(通过 Provider)、recoiljotai、zustand、mobx-react-lite(通过 observer 包装组件)、react-query(通过 QueryClientProvider,但通常只在根组件一次)// react-redux 需要顶层 Provider
<Provider store={store}>...</Provider>
// recoil 需要
<RecoilRoot>...</RecoilRoot>
// jotai / zustand 无需任何 Provider
虽然不提供具体数字,但可观察到:
redux + react-redux 需额外引入 @reduxjs/toolkit 才能现代化开发mobx-react 比 mobx-react-lite 更重(因支持 class 组件)jotai 和 zustand 以轻量著称react-query 专注于数据获取,不解决客户端状态问题observer 自动实现细粒度订阅reselect(Redux)或 shallow 比较(Zustand)优化// zustand 使用 shallow 避免不必要重渲染
const useName = (state) => state.name;
const Name = () => {
const name = useStore(useName); // 只在 name 变化时重渲染
return <div>{name}</div>;
};
// redux 使用 reselect
const selectName = createSelector(
[state => state.user],
user => user.name
);
mobx-devtools,可追踪依赖关系在实际项目中,这些库常组合使用:
react-query + zustand:用 React Query 管理服务端数据,Zustand 管理客户端 UI 状态redux + react-query:大型应用中 Redux 管理复杂客户端状态,React Query 处理 API 数据jotai 单独使用:中小型应用中同时处理客户端状态和服务端数据(通过异步 atoms)// 示例:React Query + Zustand
// 服务端状态
const { data: user } = useQuery({ queryKey: ['user'], queryFn: fetchUser });
// 客户端状态
const darkMode = useStore(state => state.darkMode);
| 特性 | redux / react-redux | mobx-react(-lite) | recoil | jotai | zustand | react-query |
|---|---|---|---|---|---|---|
| 状态模型 | 单一不可变树 | 响应式可观察对象 | 原子化 | 原子化 | 可变对象 | 服务端状态 |
| Provider 必需 | 是 | mobx-react: 是 mobx-react-lite: 否 | 是 | 否 | 否 | 是(一次) |
| 异步处理 | 中间件 | 直接在 action | 异步 selector | 异步 atom | 直接在 action | 内置 |
| 细粒度更新 | 需手动优化 | 自动 | 自动 | 自动 | 需手动优化 | N/A |
| 学习曲线 | 陡峭 | 中等 | 中等 | 平缓 | 平缓 | 平缓 |
| 适用场景 | 大型复杂应用 | 状态频繁变化的应用 | 实验性大型应用 | 中小型应用 | 快速开发 | 任何 API 应用 |
redux + react-redux + Redux Toolkitmobx-react-litezustand 或 jotaireact-query,并搭配一个客户端状态库recoil(注意其稳定性)或 jotaimobx-react → 它已被官方标记为遗留方案记住:没有“最好”的库,只有“最适合当前项目需求”的工具。理解每种方案的核心理念,才能在架构决策中游刃有余。
选择 redux 如果你要求严格的状态可预测性、完善的开发工具(如 Redux DevTools)和成熟的中间件生态(如 redux-thunk、redux-saga)。它适合大型团队协作或需要强约束状态变更流程的项目,但需搭配 Redux Toolkit 以避免样板代码。
选择 react-query 如果你的应用重度依赖服务端数据(如 REST 或 GraphQL API),需要自动缓存、后台刷新、请求去重和错误重试等能力。它专为服务端状态设计,不应与客户端 UI 状态管理库混淆,通常与其他状态库配合使用。
选择 recoil 如果你需要原子化状态、异步 selector、时间旅行调试等高级功能,且项目能接受其仍处于实验阶段(截至 2024 年)。它适合需要复杂状态图谱和跨组件状态共享的大型应用,但需评估其长期维护风险。
选择 jotai 如果你希望采用原子化状态模型,避免 Provider 包裹,同时需要良好的 TypeScript 支持和与 React 并发特性的兼容性。它适合中大型应用中需要细粒度状态更新和复杂派生逻辑的场景,且对 bundle size 敏感的项目。
选择 mobx-react 如果你已在使用 MobX 并需要完整的 React 集成(包括 class 组件支持),但注意该包已标记为仅用于遗留项目。新项目应优先考虑 mobx-react-lite,除非你确实依赖 class 组件的 observer 功能。
选择 mobx-react-lite 如果你偏好响应式编程模型,希望以声明式方式编写可观察状态,并追求高性能的自动重渲染。它适合状态结构复杂、频繁更新且开发者熟悉 MobX 概念的团队,但需注意其学习曲线和调试工具依赖。
选择 react-redux 如果你正在使用 Redux 并需要官方推荐的 React 绑定,特别是需要兼容旧版 React 或使用 connect 高阶组件。对于新项目,建议结合 Redux Toolkit 使用,并优先采用 hooks API(useSelector/useDispatch)以简化代码。
选择 zustand 如果你追求极简 API、无 Provider 设计、直接的可变状态更新,同时需要良好的 TypeScript 支持和较小的 bundle size。它适合中小型项目或作为轻量级全局状态解决方案,尤其适合快速原型开发或对 Redux 复杂性感到负担的团队。
Redux is a predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.
You can use Redux together with React, or with any other view library. The Redux core is tiny (2kB, including dependencies), and has a rich ecosystem of addons.
Redux Toolkit is our official recommended approach for writing Redux logic. It wraps around the Redux core, and contains packages and functions that we think are essential for building a Redux app. Redux Toolkit builds in our suggested best practices, simplifies most Redux tasks, prevents common mistakes, and makes it easier to write Redux applications.
The recommended way to start new apps with React and Redux Toolkit is by using our official Redux Toolkit + TS template for Vite, or by creating a new Next.js project using Next's with-redux template.
Both of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.
# Vite with our Redux+TS template
# (using the `degit` tool to clone and extract the template)
npx degit reduxjs/redux-templates/packages/vite-template-redux my-app
# Next.js using the `with-redux` template
npx create-next-app --example with-redux my-app
We do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:
npm install @reduxjs/toolkit react-redux
For the Redux core library by itself:
npm install redux
For more details, see the Installation docs page.
The Redux core docs are located at https://redux.js.org, and include the full Redux tutorials, as well usage guides on general Redux patterns:
The Redux Toolkit docs are available at https://redux-toolkit.js.org, including API references and usage guides for all of the APIs included in Redux Toolkit.
The Redux Essentials tutorial is a "top-down" tutorial that teaches "how to use Redux the right way", using our latest recommended APIs and best practices. We recommend starting there.
The Redux Fundamentals tutorial is a "bottom-up" tutorial that teaches "how Redux works" from first principles and without any abstractions, and why standard Redux usage patterns exist.
The #redux channel of the Reactiflux Discord community is our official resource for all questions related to learning and using Redux. Reactiflux is a great place to hang out, ask questions, and learn - please come and join us there!
Redux is a valuable tool for organizing your state, but you should also consider whether it's appropriate for your situation. Please don't use Redux just because someone said you should - instead, please take some time to understand the potential benefits and tradeoffs of using it.
Here are some suggestions on when it makes sense to use Redux:
Yes, these guidelines are subjective and vague, but this is for a good reason. The point at which you should integrate Redux into your application is different for every user and different for every application.
For more thoughts on how Redux is meant to be used, please see:
The whole global state of your app is stored in an object tree inside a single store. The only way to change the state tree is to create an action, an object describing what happened, and dispatch it to the store. To specify how state gets updated in response to an action, you write pure reducer functions that calculate a new state based on the old state and the action.
Redux Toolkit simplifies the process of writing Redux logic and setting up the store. With Redux Toolkit, the basic app logic looks like:
import { createSlice, configureStore } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
incremented: state => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decremented: state => {
state.value -= 1
}
}
})
export const { incremented, decremented } = counterSlice.actions
const store = configureStore({
reducer: counterSlice.reducer
})
// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))
// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}
Redux Toolkit allows us to write shorter logic that's easier to read, while still following the original core Redux behavior and data flow.
You can find the official logo on GitHub.
This project adheres to Semantic Versioning. Every release, along with the migration instructions, is documented on the GitHub Releases page.