MobX は、透過的関数型リアクティブプログラミング (TFRP) を適用することで、状態管理をシンプルかつスケーラブルにするライブラリです。
ステートとアクションの定義 (モダン MobX 6+)
import { makeAutoObservable, observable, action, computed } from 'mobx';
class CartStore {
items = [];
constructor() {
makeAutoObservable(this);
}
get totalCount() {
return this.items.reduce((sum, item) => sum + item.quantity, 0);
}
addItem(product) {
this.items.push(product);
}
removeItem(productId) {
this.items = this.items.filter((item) => item.id !== productId);
}
}
export const cartStore = new CartStore();
リアクション (Reactions)
コンポーネントを observer でラップすることで、参照している observable 値の変更時に自動で再レンダリングされます:
autorun()
直ちに実行され、アクセスされた observable 値を記録し、それらが変化するたびに自動再実行されます:
import { autorun } from 'mobx';
const disposer = autorun(() => {
console.log(`Cart total count: ${cartStore.totalCount}`);
});
// 監視を停止
disposer();
reaction()
データ追跡と副作用の実行を明確に分離するきめ細やかなリアクション:
import { reaction } from 'mobx';
reaction(
() => cartStore.items.length,
(length, prevLength) => {
console.log(`Cart item count changed from ${prevLength} to ${length}`);
}
);
when()
条件関数が true を返したときに一度だけ副作用を実行:
import { when } from 'mobx';
when(
() => cartStore.totalCount > 10,
() => console.log('Eligible for bulk discount!')
);
React との統合 (mobx-react-lite)
コンポーネントを observer でラップすることで、参照している observable 値の変更時に自動で再レンダリングされます:
import React from 'react';
import { observer } from 'mobx-react-lite';
import { cartStore } from './CartStore';
export const CartSummary = observer(() => {
return (
<div>
<h2>Total Items: {cartStore.totalCount}</h2>
<button onClick={() => cartStore.addItem({ id: 1, quantity: 1 })}>
Add Item
</button>
</div>
);
});