【整理分享】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可擴充的外掛程式
【 4. Recoil 】
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 】
- 建立全域狀態#建立內部狀態巢狀狀態局部狀態空狀態
【 6. Jotai 】
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> ); }
【 7.Zustand】
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狀態管理工具的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Java框架與React框架的整合:步驟:設定後端Java框架。建立專案結構。配置建置工具。建立React應用程式。編寫RESTAPI端點。配置通訊機制。實戰案例(SpringBoot+React):Java程式碼:定義RESTfulAPI控制器。 React程式碼:取得並顯示API回傳的資料。

Go語言作為一種快速、高效的程式語言,在後端開發領域廣受歡迎。然而,很少有人將Go語言與前端開發聯繫起來。事實上,使用Go語言進行前端開發不僅可以提高效率,還能為開發者帶來全新的視野。本文將探討使用Go語言進行前端開發的可能性,並提供具體的程式碼範例,幫助讀者更了解這一領域。在傳統的前端開發中,通常會使用JavaScript、HTML和CSS來建立使用者介面

Vue.js適合中小型項目和快速迭代,React適用於大型複雜應用。 1)Vue.js易於上手,適用於團隊經驗不足或項目規模較小的情況。 2)React的生態系統更豐富,適合有高性能需求和復雜功能需求的項目。

React通過JSX與HTML結合,提升用戶體驗。 1)JSX嵌入HTML,使開發更直觀。 2)虛擬DOM機制優化性能,減少DOM操作。 3)組件化管理UI,提高可維護性。 4)狀態管理和事件處理增強交互性。

前端工程師職責解析:主要做什麼工作?隨著互聯網的快速發展,前端工程師作為一個非常重要的職業角色,扮演著連接使用者與網站應用程式的橋樑,起著至關重要的作用。那麼,前端工程師主要做些什麼工作呢?本文將對前端工程師的職責進行解析,讓我們來一探究竟。一、前端工程師的基本職責網站開發與維護:前端工程師負責網站的前端開發工作,包括編寫網站的HTML、CSS和JavaScr

NetflixusesAcustomFrameworkcalled“ Gibbon” BuiltonReact,notReactorVuedIrectly.1)TeamSperience:selectBasedonFamiliarity.2)ProjectComplexity:vueforsimplerprojects:reactforforforproproject,reactforforforcompleplexones.3)cocatizationneedneeds:reactoffipicatizationneedneedneedneedneedneeds:reactoffersizationneedneedneedneedneeds:reactoffersizatization needefersmoreflexibleise.4)

React的優勢在於其靈活性和高效性,具體表現在:1)組件化設計提高了代碼重用性;2)虛擬DOM技術優化了性能,特別是在處理大量數據更新時;3)豐富的生態系統提供了大量第三方庫和工具。通過理解React的工作原理和使用示例,可以掌握其核心概念和最佳實踐,從而構建高效、可維護的用戶界面。

React生態系統包括狀態管理庫(如Redux)、路由庫(如ReactRouter)、UI組件庫(如Material-UI)、測試工具(如Jest)和構建工具(如Webpack)。這些工具協同工作,幫助開發者高效開發和維護應用,提高代碼質量和開發效率。
