登录  /  注册
首页 > web前端 > js教程 > 正文

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

青灯夜游
发布: 2023-04-26 17:47:48
转载
1910人浏览过

【整理分享】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 }) => 
           <span>Seconds passed: {timer.secondsPassed}
</span>)

ReactDOM.render(<TimerView timer={myTimer} />, document.body)
登录后复制

【 2. Redux 】

Redux

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

import { createStore } from &#39;redux&#39;

/**
 * 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&#39;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&#39;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&#39;s not required.
 */
function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case &#39;counter/incremented&#39;:
      return { value: state.value + 1 }
    case &#39;counter/decremented&#39;:
      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&#39;d use a view binding library (e.g. React Redux) rather than subscribe() directly.
// There may be additional use cases where it&#39;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: &#39;counter/incremented&#39; })
// {value: 1}
store.dispatch({ type: &#39;counter/incremented&#39; })
// {value: 2}
store.dispatch({ type: &#39;counter/decremented&#39; })
// {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<RootModel>()({
  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 &#39;react&#39;;
import {
  RecoilRoot,
  atom,
  selector,
  useRecoilState,
  useRecoilValue,
} from &#39;recoil&#39;;

function App() {
  return (
    <RecoilRoot>
      <CharacterCounter />
    </RecoilRoot>
  );
}
登录后复制

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

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

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

function CharacterCounter() {
  return (
    <div>
      <TextInput />
      <CharacterCount />
    </div>
  );
}

function TextInput() {
  const [text, setText] = useRecoilState(textState);

  const onChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div>
      <input type="text" value={text} onChange={onChange} />
      <br />
      Echo: {text}
    </div>
  );
}
登录后复制

【 5. Hookstate 】

hookState

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

它的主要特点包括:

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

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

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

【 6. Jotai 】

Jotai

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

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

import { atom, useAtom } from &#39;jotai&#39;;

const countAtom = atom(0);

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

  return (
    <div>
      <h1>Count: {count}</h1>

      <button onClick={() => setCount(count + 1)}>Increment</button>

      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}
登录后复制

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

【 7. Zustand】

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

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

Zustand Code

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

import create from &#39;zustand&#39;

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 (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  )
}
登录后复制

使用Zustand也非常的简单!

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

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

函数 increment 和 decrement 。

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

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

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

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

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

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

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

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

以上就是【整理分享】7个热门的React状态管理工具的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:掘金社区网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

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