redux vs react-query vs recoil vs jotai vs mobx-react vs mobx-react-lite vs react-redux vs zustand
React 状态管理与数据获取库的深度对比
reduxreact-queryrecoiljotaimobx-reactmobx-react-litereact-reduxzustand类似的npm包:

React 状态管理与数据获取库的深度对比

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 应用状态管理的完整工具链。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
redux63,946,01561,439290 kB173 年前MIT
react-query2,009,03350,5332.26 MB1124 年前MIT
recoil557,48419,4052.21 MB3204 年前MIT
jotai021,307113 kB31 个月前MIT
mobx-react028,217403 kB1411 天前MIT
mobx-react-lite028,217352 kB1411 天前MIT
react-redux023,427874 kB1510 天前MIT
zustand058,899112 kB210 小时前MIT

React 状态管理与数据获取库深度对比:从 Redux 到 Zustand

在现代 React 开发中,状态管理远不止 useState 和 useReducer。面对全局状态、服务端数据同步、性能优化等挑战,社区涌现出多种解决方案。本文将深入对比 jotai、mobx-react、mobx-react-lite、react-query、react-redux、recoil、redux 和 zustand,帮助你在真实项目中做出明智选择。

重要提示:mobx-react 已在官方文档中标记为“仅用于遗留项目”,新项目应使用 mobx-react-lite。本文仍包含它以供迁移参考。

🧠 核心理念:状态模型的根本差异

不同库对“状态”本身的理解截然不同,这直接影响了代码组织方式。

全局单一状态树(Redux)

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)

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)

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)

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)

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:中间件驱动

通过 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]);

MobX:直接在 action 中调用

异步逻辑可直接写在 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;
    }
  }
}

Recoil / Jotai:异步 Selectors

通过异步 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();
});

Zustand:直接在 actions 中处理

类似 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:专为异步设计

内置加载、错误、重试、缓存等机制,无需手动管理状态。

// react-query
const { data, error, isLoading, refetch } = useQuery({
  queryKey: ['user', id],
  queryFn: () => api.getUser(id),
  retry: 3,
  staleTime: 5000
});

📦 项目集成复杂度

Provider 必要性

  • 需要 Provider:react-redux、mobx-react(通过 Provider)、recoil
  • 无需 Provider:jotai、zustand、mobx-react-lite(通过 observer 包装组件)、react-query(通过 QueryClientProvider,但通常只在根组件一次)
// react-redux 需要顶层 Provider
<Provider store={store}>...</Provider>

// recoil 需要
<RecoilRoot>...</RecoilRoot>

// jotai / zustand 无需任何 Provider

Bundle Size 与依赖

虽然不提供具体数字,但可观察到:

  • redux + react-redux 需额外引入 @reduxjs/toolkit 才能现代化开发
  • mobx-react 比 mobx-react-lite 更重(因支持 class 组件)
  • jotai 和 zustand 以轻量著称
  • react-query 专注于数据获取,不解决客户端状态问题

🔁 状态更新粒度与性能

细粒度更新

  • Recoil / Jotai:天然支持,只有使用特定 atom 的组件会重渲染
  • MobX:通过 observer 自动实现细粒度订阅
  • Redux / Zustand:默认整个状态对象更新会触发所有订阅者,但可通过 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
);

🧪 调试与开发体验

  • Redux:拥有最成熟的 DevTools,支持时间旅行、action 日志等
  • MobX:提供 mobx-devtools,可追踪依赖关系
  • Recoil:有官方 DevTools 扩展
  • Jotai / Zustand:依赖 React DevTools,部分调试能力有限
  • React Query:提供 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-reduxmobx-react(-lite)recoiljotaizustandreact-query
状态模型单一不可变树响应式可观察对象原子化原子化可变对象服务端状态
Provider 必需是mobx-react: 是
mobx-react-lite: 否
是否否是(一次)
异步处理中间件直接在 action异步 selector异步 atom直接在 action内置
细粒度更新需手动优化自动自动自动需手动优化N/A
学习曲线陡峭中等中等平缓平缓平缓
适用场景大型复杂应用状态频繁变化的应用实验性大型应用中小型应用快速开发任何 API 应用

💡 最终建议

  • 如果你需要最强的可预测性和工具链 → 选 redux + react-redux + Redux Toolkit
  • 如果你喜欢响应式编程且状态复杂 → 选 mobx-react-lite
  • 如果你追求极简且讨厌 Provider → 选 zustand 或 jotai
  • 如果你主要处理 API 数据 → 选 react-query,并搭配一个客户端状态库
  • 如果你需要原子化状态和高级派生 → 评估 recoil(注意其稳定性)或 jotai
  • 避免在新项目中使用 mobx-react → 它已被官方标记为遗留方案

记住:没有“最好”的库,只有“最适合当前项目需求”的工具。理解每种方案的核心理念,才能在架构决策中游刃有余。

如何选择: redux vs react-query vs recoil vs jotai vs mobx-react vs mobx-react-lite vs react-redux vs zustand

  • redux:

    选择 redux 如果你要求严格的状态可预测性、完善的开发工具(如 Redux DevTools)和成熟的中间件生态(如 redux-thunk、redux-saga)。它适合大型团队协作或需要强约束状态变更流程的项目,但需搭配 Redux Toolkit 以避免样板代码。

  • react-query:

    选择 react-query 如果你的应用重度依赖服务端数据(如 REST 或 GraphQL API),需要自动缓存、后台刷新、请求去重和错误重试等能力。它专为服务端状态设计,不应与客户端 UI 状态管理库混淆,通常与其他状态库配合使用。

  • recoil:

    选择 recoil 如果你需要原子化状态、异步 selector、时间旅行调试等高级功能,且项目能接受其仍处于实验阶段(截至 2024 年)。它适合需要复杂状态图谱和跨组件状态共享的大型应用,但需评估其长期维护风险。

  • jotai:

    选择 jotai 如果你希望采用原子化状态模型,避免 Provider 包裹,同时需要良好的 TypeScript 支持和与 React 并发特性的兼容性。它适合中大型应用中需要细粒度状态更新和复杂派生逻辑的场景,且对 bundle size 敏感的项目。

  • mobx-react:

    选择 mobx-react 如果你已在使用 MobX 并需要完整的 React 集成(包括 class 组件支持),但注意该包已标记为仅用于遗留项目。新项目应优先考虑 mobx-react-lite,除非你确实依赖 class 组件的 observer 功能。

  • mobx-react-lite:

    选择 mobx-react-lite 如果你偏好响应式编程模型,希望以声明式方式编写可观察状态,并追求高性能的自动重渲染。它适合状态结构复杂、频繁更新且开发者熟悉 MobX 概念的团队,但需注意其学习曲线和调试工具依赖。

  • react-redux:

    选择 react-redux 如果你正在使用 Redux 并需要官方推荐的 React 绑定,特别是需要兼容旧版 React 或使用 connect 高阶组件。对于新项目,建议结合 Redux Toolkit 使用,并优先采用 hooks API(useSelector/useDispatch)以简化代码。

  • zustand:

    选择 zustand 如果你追求极简 API、无 Provider 设计、直接的可变状态更新,同时需要良好的 TypeScript 支持和较小的 bundle size。它适合中小型项目或作为轻量级全局状态解决方案,尤其适合快速原型开发或对 Redux 复杂性感到负担的团队。

redux的README

Redux Logo

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.

GitHub Workflow Status npm version npm downloads redux channel on discord

Installation

Create a React Redux App

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.

Documentation

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.

Learn Redux

Redux Essentials Tutorial

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.

Redux Fundamentals Tutorial

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.

Help and Discussion

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!

Before Proceeding Further

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:

  • You have reasonable amounts of data changing over time
  • You need a single source of truth for your state
  • You find that keeping all your state in a top-level component is no longer sufficient

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:

Basic Example

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.

Logo

You can find the official logo on GitHub.

Change Log

This project adheres to Semantic Versioning. Every release, along with the migration instructions, is documented on the GitHub Releases page.

License

MIT