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