您好,欢迎访问一九零五行业门户网

【整理分享】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 '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<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 'react';import { recoilroot, atom, selector, userecoilstate, userecoilvalue,} from 'recoil';function app() { return ( <recoilroot> <charactercounter /> </recoilroot> );}
一个 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 ( <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 'jotai';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 '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 ( <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状态管理工具的详细内容。
其它类似信息

推荐信息