💻 Dev

🛠️ 처음부터 만드는 State Machine — 상태 전이를 코드로 제어하기

문제


버튼 하나에 `isLoading`, `isError`, `isSuccess`, `isIdle` 플래그 4개가 붙어 있다면?
```js
// ❌ 플래그 지옥 — 동시에 isLoading=true, isError=true가 될 수 있다
let isIdle = true;
let isLoading = false;
let isError = false;
let isSuccess = false;
```
불가능한 상태 조합이 생기고, 조건문이 기하급수적으로 늘어납니다. State Machine은 "현재 상태에서 이 이벤트가 오면 → 다음 상태는 이것"이라는 규칙을 명시해서 이 문제를 원천 차단합니다.
---

코드 — 60줄 State Machine


```js
function createMachine(config) {
let currentState = config.initial;
const listeners = new Set();
function transition(event) {
const stateConfig = config.states[currentState];
if (!stateConfig) throw new Error(`Unknown state: ${currentState}`);
const transitionConfig = stateConfig.on?.[event];
if (!transitionConfig) return currentState; // 허용되지 않은 이벤트는 무시
const nextState = typeof transitionConfig === 'string'
? transitionConfig
: transitionConfig.target;
// exit action 실행
stateConfig.exit?.();
// transition action 실행
if (typeof transitionConfig === 'object') {
transitionConfig.action?.();
}
currentState = nextState;
// enter action 실행
config.states[currentState]?.enter?.();
// 구독자에게 알림
listeners.forEach(fn => fn(currentState));
return currentState;
}
function getState() {
return currentState;
}
function subscribe(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
}
// 초기 상태 enter action
config.states[currentState]?.enter?.();
return { transition, getState, subscribe };
}
```
---

사용 예제 — Fetch 상태 관리


```js
const fetchMachine = createMachine({
initial: 'idle',
states: {
idle: {
on: { FETCH: 'loading' },
enter: () => console.log('→ 대기 중'),
},
loading: {
on: {
SUCCESS: 'success',
ERROR: 'error',
},
enter: () => console.log('→ 로딩 중...'),
},
success: {
on: { RESET: 'idle' },
enter: () => console.log('→ 성공!'),
},
error: {
on: {
RETRY: { target: 'loading', action: () => console.log('재시도!') },
RESET: 'idle',
},
enter: () => console.log('→ 에러 발생'),
},
},
});
// 상태 변화 구독
const unsubscribe = fetchMachine.subscribe(state => {
console.log(`[구독] 현재 상태: ${state}`);
});
fetchMachine.transition('FETCH'); // → 로딩 중...
fetchMachine.transition('ERROR'); // → 에러 발생
fetchMachine.transition('RETRY'); // 재시도! → 로딩 중...
fetchMachine.transition('SUCCESS'); // → 성공!
fetchMachine.transition('FETCH'); // 무시됨 (success에서 FETCH 불가)
fetchMachine.transition('RESET'); // → 대기 중
console.log(fetchMachine.getState()); // 'idle'
unsubscribe();
```
---

핵심 설명


| 개념 | 설명 |
|------|------|
| State (상태) | `idle`, `loading` 등 시스템이 존재할 수 있는 모드 |
| Event (이벤트) | `FETCH`, `SUCCESS` 등 상태 전이를 일으키는 트리거 |
| Transition (전이) | "이 상태에서 이 이벤트 → 저 상태"라는 규칙 |
| Action (액션) | 전이 시 실행되는 부수 효과 (`enter`, `exit`, `action`) |
왜 좋은가?
1. 불가능한 상태가 원천 차단 — `loading`이면서 `success`인 상태는 존재 불가
2. 허용되지 않은 전이 무시 — `success`에서 `FETCH`를 보내도 아무 일 없음
3. 시각화 가능 — 상태 다이어그램으로 바로 그릴 수 있는 구조
---

프로덕션에서는?


직접 구현 대신 XState를 사용하세요. 중첩 상태, 병렬 상태, guard, context 등 실무에 필요한 기능을 모두 제공합니다.
```bash
npm install xstate
```
📚 공식 문서: [https://stately.ai/docs/xstate](https://stately.ai/docs/xstate)
> 상태를 boolean 플래그로 관리하고 있다면, State Machine 도입을 고려해 보세요. 버그가 줄고, 코드가 읽기 쉬워집니다.
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!