大家都說(shuō) Jotai 好,那就來(lái)個(gè)大PK!
昨天發(fā)了一篇文章,分享了 Recoil 停止更新的情況,并推薦了當(dāng)前熱門的 React 狀態(tài)管理工具 Zustand。文章發(fā)布后,評(píng)論區(qū)不少同學(xué)表示 Jotai 在使用體驗(yàn)上更勝一籌。鑒于此,今天就來(lái)看看主流 React 狀態(tài)管理庫(kù)的使用方式,看看哪個(gè)更合你意!
總覽
不得不承認(rèn),React 生態(tài)系統(tǒng)實(shí)在是太豐富了,僅狀態(tài)管理這一領(lǐng)域就提供了諸多選項(xiàng),且持續(xù)有新工具涌現(xiàn)。當(dāng)前,React 狀態(tài)管理的主流庫(kù)包括 Redux、Zustand、MobX、Recoil、Jotai 等。其中,Redux 以遙遙領(lǐng)先的下載量獨(dú)占鰲頭,不過(guò)其增長(zhǎng)速度有所放緩;而 Zustand 則緊隨其后,尤其在近兩年展現(xiàn)出迅猛的增長(zhǎng)勢(shì)頭,成為不可忽視的力量。
Redux
特點(diǎn)
Redux 是一個(gè)老牌的全局狀態(tài)管理庫(kù),它的核心思想如下:
- 單一數(shù)據(jù)源:整個(gè)應(yīng)用的狀態(tài)被存儲(chǔ)在一個(gè)單一的對(duì)象樹中,即 store。這使得狀態(tài)的管理和調(diào)試變得更加簡(jiǎn)單和直觀。
- 狀態(tài)是只讀的:在 Redux 里,不能直接去修改 store 中的狀態(tài)。所有的狀態(tài)變更都必須通過(guò)觸發(fā)特定的動(dòng)作(action)來(lái)發(fā)起請(qǐng)求。這種方式確保了狀態(tài)的變化是可追蹤的,避免了直接修改狀態(tài)帶來(lái)的問題。
- 使用純函數(shù)來(lái)執(zhí)行修改:Reducer 是一個(gè)純函數(shù),它接受當(dāng)前狀態(tài)和一個(gè) action 作為參數(shù),并返回新的狀態(tài)。Reducer 不會(huì)修改傳入的狀態(tài),而是返回一個(gè)新的狀態(tài)對(duì)象。這種設(shè)計(jì)使得狀態(tài)更新邏輯是可預(yù)測(cè)的,并且易于測(cè)試和維護(hù)。
基本使用
- 創(chuàng)建 Action(動(dòng)作)
- 定義: Action 是一個(gè)普通的 JavaScript 對(duì)象,用于描述應(yīng)用中發(fā)生了什么事情,也就是表明想要對(duì)狀態(tài)進(jìn)行何種改變。它就像是一個(gè)指令,告知 Redux 系統(tǒng)接下來(lái)需要執(zhí)行的操作任務(wù)。
- 結(jié)構(gòu): 每個(gè) Action 通常都包含一個(gè)必須的type屬性,其值為一個(gè)字符串,用于唯一標(biāo)識(shí)這個(gè)動(dòng)作的類型,讓 Reducer 能夠根據(jù)這個(gè)類型來(lái)判斷該如何處理該動(dòng)作。除此之外,還可以根據(jù)具體需求在 Action 對(duì)象中攜帶其他的數(shù)據(jù)(通常放在payload屬性中),這些數(shù)據(jù)就是執(zhí)行對(duì)應(yīng)操作所需要的具體信息。
// actions.js
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
- 創(chuàng)建 Reducer: Reducer 是一個(gè)純函數(shù),它接收兩個(gè)參數(shù):當(dāng)前的整個(gè)狀態(tài)樹(作為第一個(gè)參數(shù))以及一個(gè) Action(作為第二個(gè)參數(shù)),然后根據(jù) Action 的類型(通過(guò)
type
屬性來(lái)判斷)來(lái)決定如何更新狀態(tài),并返回一個(gè)新的狀態(tài)。
// reducer.js
import { INCREMENT, DECREMENT } from './actions';
const initialState = {
count: 0
};
function counterReducer(state = initialState, action) {
switch (action.type) {
case INCREMENT:
return { ...state, count: state.count + 1 };
case DECREMENT:
return { ...state, count: state.count - 1 };
default:
return state;
}
}
export default counterReducer;
- 創(chuàng)建 Store(狀態(tài)容器):Store 是整個(gè) Redux 架構(gòu)的核心,它把狀態(tài)(State)、Reducer 函數(shù)以及一些用于訂閱狀態(tài)變化的方法等都整合在一起,是整個(gè)應(yīng)用狀態(tài)的存儲(chǔ)中心和管理樞紐。創(chuàng)建 Store 時(shí)需要傳入一個(gè)根 Reducer:
// store.js
import { createStore } from 'redux';
import counterReducer from './reducer';
const store = createStore(counterReducer);
export default store;
- 在 React 組件中使用 Redux:使用 Provider 組件將 store 提供給整個(gè) React 應(yīng)用,并使用 useSelector 和 useDispatch 鉤子來(lái)訪問和更新狀態(tài):
// App.js
import React from 'react';
import { Provider, useSelector, useDispatch } from 'react-redux';
import store from './store';
import { increment, decrement } from './actions';
function Counter() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
export default App;
缺點(diǎn)
- 過(guò)于復(fù)雜: 對(duì)于小型項(xiàng)目或者簡(jiǎn)單應(yīng)用來(lái)說(shuō),Redux 可能顯得過(guò)于復(fù)雜。它的概念(如 action、reducer、store)和工作流程需要一定的時(shí)間去理解和掌握。
- 代碼冗余:Redux 需要編寫大量的模板代碼,包括定義 actions、reducers 和配置 store,這可能會(huì)增加開發(fā)的初始成本。
- 異步處理復(fù)雜: Redux 默認(rèn)只支持同步處理,處理異步操作需要使用中間件,如
redux-thunk
或redux-saga
。這些中間件雖然強(qiáng)大,但增加了代碼的復(fù)雜性和學(xué)習(xí)成本。
Zustand
特點(diǎn)
Zustand 是一個(gè)輕量級(jí)狀態(tài)管理庫(kù),專為 React 應(yīng)用設(shè)計(jì)。它提供了簡(jiǎn)單直觀的 API,旨在減少樣板代碼,并且易于集成和使用。其特點(diǎn)如下:
- 簡(jiǎn)潔性:Zustand 的設(shè)計(jì)理念是保持極簡(jiǎn)主義,通過(guò)簡(jiǎn)單的 API 和最小化的配置來(lái)實(shí)現(xiàn)高效的狀態(tài)管理。
- 基于 Hooks:它完全依賴于 React 的 Hooks 機(jī)制,允許開發(fā)者以聲明式的方式訂閱狀態(tài)變化并觸發(fā)更新。
- 無(wú)特定立場(chǎng):Zustand 不強(qiáng)制任何特定的設(shè)計(jì)模式或結(jié)構(gòu),給予開發(fā)者最大的靈活性。
- 單一數(shù)據(jù)源:盡管 Zustand 支持多個(gè)獨(dú)立的 store,但每個(gè) store 內(nèi)部仍然遵循單一數(shù)據(jù)源的原則,即所有狀態(tài)都集中存儲(chǔ)在一個(gè)地方。
- 模塊化狀態(tài)切片:狀態(tài)可以被分割成不同的切片(slices),每個(gè)切片負(fù)責(zé)一部分應(yīng)用邏輯,便于管理和維護(hù)。
- 異步支持:Zustand 可以輕松處理異步操作,允許在 store 中定義異步函數(shù)來(lái)執(zhí)行如 API 請(qǐng)求等任務(wù)。
基本使用
創(chuàng)建 Store:在 Zustand 中,Store是通過(guò)create
函數(shù)創(chuàng)建的。每個(gè)Store都包含狀態(tài)和處理狀態(tài)的函數(shù)。
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0, // 初始狀態(tài)
increment: () => set((state) => ({ count: state.count + 1 })), // 增加count的函數(shù)
decrement: () => set((state) => ({ count: state.count - 1 })), // 減少count的函數(shù)
}));
create函數(shù)接受一個(gè)回調(diào)函數(shù),該回調(diào)函數(shù)接受一個(gè)set函數(shù)作為參數(shù),用于更新狀態(tài)。在這個(gè)回調(diào)函數(shù)中,定義了一個(gè)count狀態(tài)和兩個(gè)更新函數(shù)increment和decrement。
使用 Store:在組件中,可以使用自定義的 Hooks(上面的useStore)來(lái)獲取狀態(tài)和更新函數(shù),并在組件中使用它們。
import React from 'react';
import { useStore } from './store';
function Counter() {
const { count, increment, decrement } = useStore();
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
訂閱特定狀態(tài)片段如果有一個(gè)包含多個(gè)狀態(tài)的store,但在組件中只需要訂閱其中一個(gè)狀態(tài),可以通過(guò)解構(gòu)賦值從useStore返回的完整狀態(tài)對(duì)象中提取需要的狀態(tài)。Zustand的智能選擇器功能允許這樣做,而不會(huì)導(dǎo)致不必要的重新渲染。
// store.js
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0,
name: 'Zustand Store',
increment: () => set((state) => ({ count: state.count + 1 })),
setName: (newName) => set({ name: newName }),
}));
export default useStore;
在組件中,如果只想訂閱count狀態(tài),可以這樣做:
// MyComponent.js
import React from 'react';
import useStore from './store';
function MyComponent() {
const { count } = useStore((state) => ({ count: state.count }));
return (
<div>
<p>Count: {count}</p>
</div>
);
}
export default MyComponent;
Mobx
特點(diǎn)
MobX 是一個(gè)簡(jiǎn)單、可擴(kuò)展的狀態(tài)管理庫(kù)。它通過(guò)透明的函數(shù)響應(yīng)式編程使得狀態(tài)管理變得簡(jiǎn)單和高效。其核心思想如下:
- 可觀察對(duì)象:MobX 通過(guò) observable 裝飾器將數(shù)據(jù)標(biāo)記為可觀察的,當(dāng)這些數(shù)據(jù)發(fā)生變化時(shí),依賴于這些數(shù)據(jù)的組件會(huì)自動(dòng)更新。
- 計(jì)算屬性:計(jì)算屬性是基于可觀察狀態(tài)的派生值,它們會(huì)自動(dòng)更新以反映基礎(chǔ)狀態(tài)的變化。
- 響應(yīng)式函數(shù):用于修改可觀察狀態(tài)的函數(shù),MobX 會(huì)自動(dòng)追蹤這些函數(shù)中的狀態(tài)讀寫操作,并通知相關(guān)的觀察者進(jìn)行更新。
- 自動(dòng)依賴追蹤:MobX 會(huì)自動(dòng)追蹤代碼中對(duì)可觀察狀態(tài)的訪問,建立起一個(gè)依賴關(guān)系圖,當(dāng)可觀察狀態(tài)發(fā)生變化時(shí),會(huì)通知所有依賴于該狀態(tài)的觀察者進(jìn)行更新
基本使用
創(chuàng)建 Store: Store 是存儲(chǔ)應(yīng)用狀態(tài)的地方,并提供修改這些狀態(tài)的方法。MobX 提供了多種方式來(lái)定義可觀察的狀態(tài)和操作這些狀態(tài)的動(dòng)作。
- 使用 makeAutoObservabl:這是最推薦的方式,因?yàn)樗苊饬耸褂醚b飾器(Babel 插件等),簡(jiǎn)化了代碼。
import { makeAutoObservable } from 'mobx';
class CounterStore {
count = 0;
constructor() {
makeAutoObservable(this);
}
increment = () => {
this.count++;
};
decrement = () => {
this.count--;
};
}
// 創(chuàng)建全局 store 實(shí)例
const counterStore = new CounterStore();
export default counterStore;
在函數(shù)組件中使用 Store:對(duì)于函數(shù)組件,可以使用 useObserver Hook 來(lái)確保組件能夠響應(yīng)可觀察對(duì)象的變化。如果你需要在組件內(nèi)部創(chuàng)建局部的可觀察狀態(tài),則可以使用 useLocalStore。
- 使用全局 Store (counterStore)
import React from 'react';
import { useObserver } from 'mobx-react';
import counterStore from './CounterStore';
const Counter = () => {
return useObserver(() => (
<div>
<p>Count: {counterStore.count}</p>
<button onClick={() => counterStore.increment()}>Increment</button>
<button onClick={() => counterStore.decrement()}>Decrement</button>
</div>
));
};
export default Counter;
- 使用局部 Store (useLocalStore):如果需要?jiǎng)?chuàng)建局部可觀察狀態(tài),可以這樣做:
import React from 'react';
import { useObserver, useLocalStore } from 'mobx-react';
const Counter = () => {
const store = useLocalStore(() => ({
count: 0,
increment: () => {
this.count++;
},
decrement: () => {
this.count--;
}
}));
return useObserver(() => (
<div>
<p>Count: {store.count}</p>
<button onClick={store.increment}>Increment</button>
<button onClick={store.decrement}>Decrement</button>
</div>
));
};
export default Counter;
注意:通常情況下,應(yīng)該盡量使用全局 store,除非有明確的理由需要局部狀態(tài)。
在類組件中使用 Store:對(duì)于類組件,可以使用 observer 高階組件(HOC)來(lái)將組件與 MobX 的狀態(tài)管理連接起來(lái)。observer 會(huì)自動(dòng)檢測(cè)組件中使用的可觀察對(duì)象,并且當(dāng)這些對(duì)象發(fā)生變化時(shí),會(huì)重新渲染組件。
import React from 'react';
import { observer } from 'mobx-react';
import counterStore from './CounterStore'; // 確保路徑正確
class Counter extends React.Component {
handleIncrement = () => {
counterStore.increment();
};
handleDecrement = () => {
counterStore.decrement();
};
render() {
return (
<div>
<p>Count: {counterStore.count}</p>
<button onClick={this.handleIncrement}>Increment</button>
<button onClick={this.handleDecrement}>Decrement</button>
</div>
);
}
}
export default observer(Counter);
使用計(jì)算屬性和反應(yīng): 除了直接操作狀態(tài)外,MobX 還提供了 computed 和 reaction 等功能,用于基于現(xiàn)有狀態(tài)派生新值或監(jiān)聽狀態(tài)變化并執(zhí)行副作用。
- 計(jì)算屬性 (computed)
import { makeAutoObservable, computed } from 'mobx';
class CounterStore {
count = 0;
constructor() {
makeAutoObservable(this);
}
increment = () => {
this.count++;
};
decrement = () => {
this.count--;
};
@computed get doubleCount() {
return this.count * 2;
}
}
const counterStore = new CounterStore();
export default counterStore;
- 反應(yīng) (reaction)
import { reaction } from 'mobx';
reaction(
() => counterStore.count, // 跟蹤的依賴
(count) => console.log(`Count changed to ${count}`) // 當(dāng)依賴變化時(shí)觸發(fā)的回調(diào)
);
Recoil
特點(diǎn)
Recoil 是由 Facebook 開發(fā)的一個(gè)用于 React 狀態(tài)管理庫(kù),目前已停止維護(hù)。它旨在提供一種簡(jiǎn)單、高效的方式來(lái)管理組件間共享的狀態(tài)。其核心思想如下:
- 原子狀態(tài):Recoil 將狀態(tài)劃分為原子,每個(gè)原子是一個(gè)獨(dú)立的狀態(tài)片段,可以被任何 React 組件訪問和訂閱。
- 選擇器:選擇器是基于原子狀態(tài)派生的狀態(tài),通過(guò)純函數(shù)來(lái)計(jì)算。它們可以同步或異步地轉(zhuǎn)換狀態(tài)。類似于 Redux 中的 reducer 或 MobX 中的 computed 屬性。
- 細(xì)粒度依賴跟蹤:Recoil 內(nèi)置了高效的依賴跟蹤機(jī)制,只有當(dāng)組件實(shí)際依賴的狀態(tài)發(fā)生變化時(shí)才會(huì)觸發(fā)重新渲染。
- 單向數(shù)據(jù)流與響應(yīng)式更新Recoil 遵循單向數(shù)據(jù)流原則,組件通過(guò)訂閱原子或選擇器來(lái)獲取狀態(tài),當(dāng)有事件觸發(fā)狀態(tài)更新時(shí),狀態(tài)的變化會(huì)沿著數(shù)據(jù)流從原子、選擇器流向訂閱它們的組件,觸發(fā)組件重新渲染,從而更新 UI。
基本使用
創(chuàng)建 Atom 和 Selector:
- 原子創(chuàng)建: 定義一個(gè) atom 來(lái)表示應(yīng)用中的某個(gè)狀態(tài)片段。
import { atom } from 'recoil';
export const counterState = atom({
key: 'counterState',
default: 0,
});
- 創(chuàng)建 Selector:定義一個(gè) selector 來(lái)計(jì)算派生狀態(tài)或執(zhí)行異步操作。
import { selector } from 'recoil';
import { counterState } from './atoms';
export const doubleCounterSelector = selector({
key: 'doubleCounterSelector',
get: ({ get }) => {
const count = get(counterState);
return count * 2;
},
});
使用 Atom 和 Selector:
- 在組件中使用 useRecoilState Hook 來(lái)獲取原子狀態(tài)并更新(適用于讀寫原子狀態(tài)的場(chǎng)景)。
import React from 'react';
import { useRecoilState } from 'recoil';
import { counterState } from './atoms';
const Counter = () => {
const [count, setCount] = useRecoilState(counterState);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
};
export default Counter;
- 在組件中使用 useRecoilValue Hook 僅獲取原子或選擇器的值(適用于只讀場(chǎng)景):
import React from 'react';
import { useRecoilValue } from 'recoil';
import { doubleCounterSelector } from './selectors';
const DoubleCounter = () => {
const doubleCount = useRecoilValue(doubleCounterSelector);
return <p>Double Count: {doubleCount}</p>;
};
export default DoubleCounter;
- 使用 useSetRecoilState Hook 僅獲取更新原子狀態(tài)的函數(shù)(適用于只寫場(chǎng)景):
import React from 'react';
import { useSetRecoilState } from'recoil';
import { countAtom } from './atoms';
const IncrementButtonComponent = () => {
const setCount = useSetRecoilState(countAtom);
return (
<button onClick={() => setCount((prevCount) => prevCount + 1)}>Increment</button>
);
};
Jotai
特點(diǎn)
Jotai 是一個(gè)輕量級(jí)且靈活的 React 狀態(tài)管理庫(kù),采用原子化狀態(tài)管理模型。它受到了 Recoil 的啟發(fā),旨在提供一種簡(jiǎn)單而直觀的方式來(lái)管理 React 中的狀態(tài)。其核心思想:
- 原子化狀態(tài)管理:Jotai 使用原子作為狀態(tài)的基本單位。每個(gè)原子代表一個(gè)獨(dú)立的狀態(tài)片段,可以被多個(gè)組件共享和訪問。
- 組合性:通過(guò)組合 atoms 和選擇器,可以構(gòu)建復(fù)雜的、依賴于其他狀態(tài)的狀態(tài)邏輯。這種組合性使得狀態(tài)管理更加模塊化和靈活。
- 細(xì)粒度依賴跟蹤:Jotai 內(nèi)置了高效的依賴跟蹤機(jī)制,只有當(dāng)組件實(shí)際依賴的狀態(tài)發(fā)生變化時(shí)才會(huì)觸發(fā)重新渲染。
基本使用
創(chuàng)建 Atom:
- 簡(jiǎn)單原子創(chuàng)建:定義一個(gè) atom 來(lái)表示應(yīng)用中的某個(gè)狀態(tài)片段。
import { atom } from 'jotai';
export const countAtom = atom(0);
- 派生原子創(chuàng)建(基于已有原子進(jìn)行計(jì)算等)
import { atom } from 'jotai';
import { countAtom } from './atoms';
export const doubleCountAtom = atom((get) => get(countAtom) * 2);
使用 Atom:
- 使用 useAtom Hook 獲取和更新原子狀態(tài)(適用于讀寫原子狀態(tài)場(chǎng)景):
import React from 'react';
import { useAtom } from 'jotai';
import { countAtom } from './atoms';
const Counter = () => {
const [count, setCount] = useAtom(countAtom);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
<button onClick={() => setCount((prev) => prev - 1)}>Decrement</button>
</div>
);
};
export default Counter;
- 使用 useAtomValue Hook 僅獲取原子狀態(tài)(適用于只讀場(chǎng)景):
import React from 'react';
import { useAtomValue } from 'jotai';
import { doubleCountAtom } from './derivedAtoms';
const DoubleCounter = () => {
const doubleCount = useAtomValue(doubleCountAtom);
return <p>Double Count: {doubleCount}</p>;
};
export default DoubleCounter;
- 使用 useSetAtom Hook 僅獲取更新原子狀態(tài)的函數(shù)(適用于只寫場(chǎng)景):
import React from 'react';
import { useAtomValue } from 'jotai';
import { countAtom } from './derivedAtoms';
const IncrementButtonComponent = () => {
const setCount = useSetAtom(countAtom);
return (
<button onClick={() => setCount((prevCount) => prevCount + 1)}>Increment</button>
);
};