ステートマシンは、システムを状態の有限集合と、それらの間の許可された遷移としてモデル化します。独立したブール値フラグを扱う代わりに、どの状態が存在し、どの遷移が合法かを正確に定義します — 不可能な状態を表現できなくします。
問題: boolean soup
js
[isLoading, setLoading] = ();
[isError, setError] = ();
[isSuccess, setSuccess] = ();
独立したフラグでは、矛盾した組み合わせを止めるものはなく、すべての遷移で手動でそれらを一貫性を保つ必要があります — バグの温床です。
States: idle → loading → success
↓
error → (retry) → loading
Only defined transitions are allowed; you can't be in two states at once.
const machine = {
idle: { FETCH: "loading" },
loading: { SUCCESS: "success", ERROR: "error" },
success: { FETCH: "loading" },
error: { RETRY: "loading" },
};
function transition(current, event) {
return machine[current][event] ?? current; // only legal transitions happen
}
単一の state 変数が現在の状態を保持します。event は定義された遷移をトリガーします。不正な遷移 (例: 待機中にSUCCESS) は単純に発生できません — 不可能な状態は設計により排除されています。
// libraries like XState formalize this with guards, actions, nested/parallel states
const toggleMachine = createMachine({
initial: "inactive",
states: {
inactive: { on: { TOGGLE: "active" } },
active: { on: { TOGGLE: "inactive" } },
},
});
✓ Complex flows with many states: checkout, multi-step forms/wizards, media players
✓ Authentication flows (logged out → logging in → logged in → refreshing)
✓ Anything where invalid state combinations cause bugs
✗ Overkill for simple toggles or trivial state
ステートマシンは、無効な状態を不可能にし、遷移を明示的にすることで、複雑なステートフル・ロジックに厳密性をもたらします — ブール値の脆い組み合わせを、明確で網羅的なモデルに置き換えます。
ウィザード、支払い、認証、メディアなどの複雑なフローに特に価値があり、boolean soup が微妙で再現が難しいバグにつながる場合があります。
非公式的 (status enum) でも、この考え方は非同期状態を改善します。公式的 (XState) には、可視化可能でテスト可能で堅牢なロジックが提供されます。
いつそれを使うべきかを知ることは、成熟した状態設計の証です。