0

0

【整理分享】7个热门的React状态管理工具

青灯夜游

青灯夜游

发布时间:2023-04-26 17:47:48

|

3010人浏览过

|

来源于掘金社区

转载

【整理分享】7个热门的React状态管理工具

最近在做项目技术栈整理工作;

由于团队越来越大、人员增多、项目增多;

统一技术栈是一件非常有必要的事;

React 状态管理工具有很多,但是选择一个合适的状态管理工具其实很重要;

今天跟大家分享一下我整理的几个非常热门的 React状态管理,希望对你有所帮助。

【 1. Mobx 】

Mobx

MobX 可以独立于 React 运行, 但是他们通常是结合在一起使用;新版的 mobx-react-lite 库非常轻量;使用时只需要使用导出的observer包裹组件; 然后引入状态即可;

import React from "react"
import ReactDOM from "react-dom"
import { makeAutoObservable } from "mobx"
import { observer } from "mobx-react-lite"

class Timer {
    secondsPassed = 0

    constructor() {
        makeAutoObservable(this)
    }

    increaseTimer() {
        this.secondsPassed += 1
    }
}

const myTimer = new Timer()

//被`observer`包裹的函数式组件会被监听在它每一次调用前发生的任何变化
const TimerView = observer(({ timer }) => 
           Seconds passed: {timer.secondsPassed}
)

ReactDOM.render(, document.body)

【 2. Redux 】

Redux

Redux 也是一个非常流行的状态管理,只不过比起其他的状态管理工具,会显得笨重一些;当然喜欢使用Redux的人也会觉得Redux 非常的优雅;

import { createStore } from 'redux'

/**
 * This is a reducer - a function that takes a current state value and an
 * action object describing "what happened", and returns a new state value.
 * A reducer's function signature is: (state, action) => newState
 *
 * The Redux state should contain only plain JS objects, arrays, and primitives.
 * The root state value is usually an object. It's important that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * You can use any conditional logic you want in a reducer. In this example,
 * we use a switch statement, but it's not required.
 */
function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 }
    case 'counter/decremented':
      return { value: state.value - 1 }
    default:
      return state
  }
}

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(counterReducer)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// There may be additional use cases where it's helpful to subscribe as well.

store.subscribe(() => console.log(store.getState()))

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch({ type: 'counter/incremented' })
// {value: 1}
store.dispatch({ type: 'counter/incremented' })
// {value: 2}
store.dispatch({ type: 'counter/decremented' })
// {value: 1}

想要很快上手Redux 不是一件容易的事,还需要仔细琢磨一下; 不过好在redux官方推出了新的Redux-tookit 大大简化了使用Redux的步骤。

【 3. Rematch 】

Rematch

Rematch 延续了Redux的优点,核心概念还是基于Redux;但是比起Redux,它简直太强大了!。

import { createModel } from "@rematch/core";
import { RootModel } from ".";

export const count = createModel()({
  state: 0, // initial state
  reducers: {
    // handle state changes with pure functions
    increment(state, payload: number) {
      return state + payload;
    },
  },
  effects: (dispatch) => ({
    // handle state changes with impure functions.
    // use async/await for async actions
    async incrementAsync(payload: number, state) {
      console.log("This is current root state", state);
      await new Promise((resolve) => setTimeout(resolve, 1000));
      dispatch.count.increment(payload);
    },
  }),
});

以下是Rematch 的一些特性:

  • 小于2kb的大小
  • 不需要配置
  • 减少Redux样板文件
  • 内置副作用支持
  • React Devtools支持
  • TypeScript 原生支持
  • 支持动态添加reducers
  • 支持热重载
  • 允许创建多个store
  • 支持React Native
  • 可扩展的插件

Rematch 的store还是延续了一些Redux的写法,只不过总体是精简了许多。想要上手也是非常轻松的。

【 4. Recoil 】

Recoil

Recoil 提供了一种新的状态管理模型——Atom模型,它可以更好地处理复杂的状态逻辑。

如需在组件中使用 Recoil,则可以将 RecoilRoot 放置在父组件的某个位置。将他设为根组件为最佳:

import React from 'react';
import {
  RecoilRoot,
  atom,
  selector,
  useRecoilState,
  useRecoilValue,
} from 'recoil';

function App() {
  return (
    
      
    
  );
}

一个 atom 代表一个状态。Atom 可在任意组件中进行读写。读取 atom 值的组件隐式订阅了该 atom,因此任何 atom 的更新都将致使使用对应 atom 的组件重新渲染;

使用atom状态,需要在组件内引入 useRecoilState:

const textState = atom({
  key: 'textState', // unique ID (with respect to other atoms/selectors)
  default: '', // default value (aka initial value)
});

function CharacterCounter() {
  return (
    
); } function TextInput() { const [text, setText] = useRecoilState(textState); const onChange = (event) => { setText(event.target.value); }; return (

Echo: {text}
); }

【 5. Hookstate 】

hookState

HookState 也是一个非常简单的状态管理工具库,它直观的Api,供你轻松的访问状态;

人民网AIGC-X
人民网AIGC-X

国内科研机构联合推出的AI生成内容检测工具

下载

它的主要特点包括:

  • 创建全局状态
  • 创建内部状态
  • 嵌套状态
  • 局部状态
  • 空状态

HookState 主要包括两个重要的Api HookState、useHookState。

如果还需要其他功能,可以参考官方提供的其他更多Api。

【 6. Jotai 】

Jotai

Jotai 是一个 React 的原始和灵活的状态管理库。它类似于 Recoil,但具有更小的包大小 、更简约的 API、更好的 TypeScript 支持、更广泛的文档以及没有实验性标签。

使用Jotai,你可以将状态存储在一个单一的store中,并使用自定义的hooks来访问和更新状态。

import { atom, useAtom } from 'jotai';

const countAtom = atom(0);

function Counter() {
  const [count, setCount] = useAtom(countAtom);

  return (
    

Count: {count}

); }

以上是Jotai的使用示例代码,使用Jotai非常简单。

【 7. Zustand】

Zustand 提供了一种简单的方式来管理React应用程序中的状态。

它的主要特点是易于使用和轻量级。

Zustand Code

使用Zustand,你可以将状态存储在一个单一的store中,并使用自定义的hooks来访问和更新状态。这使得状态管理变得非常简单和直观。

import create from 'zustand'

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
}))

function Counter() {
  const { count, increment, decrement } = useStore()

  return (
    

Count: {count}

) }

使用Zustand也非常的简单!

在这个例子中,我们使用 create 函数创建了一个新的store,

并定义了一个名为 count 的状态和两个更新状态的

函数 increment 和 decrement 。

然后,我们使用 useStore 自定义 hook 来访问和更新状态。

【以上7个状态管理工具各有特点】

考虑到团队人员技术的参差不齐,未来项目的可维护、延展性;

建议大家选择入门简单,上手快的工具;

因为之前最早我们选择的是Redux,现在再回头看原来的项目,简直难以维护了。

如果你的团队还是倾向于Redux,这里建议还是使用Rematch比较好。

如果是还没使用状态管理,又想用的,建议使用mobx吧!

(学习视频分享:编程基础视频

相关专题

更多
Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

2

2026.01.14

php与html混编教程大全
php与html混编教程大全

本专题整合了php和html混编相关教程,阅读专题下面的文章了解更多详细内容。

13

2026.01.13

PHP 高性能
PHP 高性能

本专题整合了PHP高性能相关教程大全,阅读专题下面的文章了解更多详细内容。

22

2026.01.13

MySQL数据库报错常见问题及解决方法大全
MySQL数据库报错常见问题及解决方法大全

本专题整合了MySQL数据库报错常见问题及解决方法,阅读专题下面的文章了解更多详细内容。

18

2026.01.13

PHP 文件上传
PHP 文件上传

本专题整合了PHP实现文件上传相关教程,阅读专题下面的文章了解更多详细内容。

9

2026.01.13

PHP缓存策略教程大全
PHP缓存策略教程大全

本专题整合了PHP缓存相关教程,阅读专题下面的文章了解更多详细内容。

6

2026.01.13

jQuery 正则表达式相关教程
jQuery 正则表达式相关教程

本专题整合了jQuery正则表达式相关教程大全,阅读专题下面的文章了解更多详细内容。

2

2026.01.13

交互式图表和动态图表教程汇总
交互式图表和动态图表教程汇总

本专题整合了交互式图表和动态图表的相关内容,阅读专题下面的文章了解更多详细内容。

40

2026.01.13

nginx配置文件详细教程
nginx配置文件详细教程

本专题整合了nginx配置文件相关教程详细汇总,阅读专题下面的文章了解更多详细内容。

5

2026.01.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 3.6万人学习

国外Web开发全栈课程全集
国外Web开发全栈课程全集

共12课时 | 1.0万人学习

React核心原理新老生命周期精讲
React核心原理新老生命周期精讲

共12课时 | 1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号