MobX 和 Zustand 是兩個用於管理 React 應用狀態的不同庫。它們有不同的設計理念和用法,各自有其優勢和適用場景。
MobX 是一個簡單、可擴展的狀態管理庫,旨在使應用的狀態管理變得簡單和可預測。它基於響應式設計原理,通過觀察狀態變化自動更新 UI,減少了手動更新 UI 的工作。
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React from 'react';
class CounterStore {
count = 0;
constructor() {
makeAutoObservable(this);
}
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
const counterStore = new CounterStore();
const Counter = observer(() => (
<div>
<h1>{counterStore.count}</h1>
<button onClick={() => counterStore.increment()}>Increment</button>
<button onClick={() => counterStore.decrement()}>Decrement</button>
</div>
));
function App() {
return (
<div className="App">
<Counter />
</div>
);
}
export default App;
Zustand 是一個輕量級的、靈活的狀態管理庫,專為 React 應用設計。Zustand 使用簡單的 API 和 Hook,使得狀態管理變得非常直觀。