Files
2nd/10_Wiki/Topics/Domain_Programming/Coding/React_Reducer_useReducer.md
T
Antigravity Agent c24165b8bc refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 11:05:56 +09:00

3.4 KiB

id, title, category, status, source_trust_level, verification_status, created_at, updated_at, tags, tech_stack, applied_in, aliases
id title category status source_trust_level verification_status created_at updated_at tags tech_stack applied_in aliases
react-reducer-usereducer useReducer — 복잡 상태 전이 Coding draft B conceptual 2026-05-09 2026-05-09
react
reducer
state-machine
vibe-coding
language applicable_to
TypeScript / React 18+
Web
React Native
useReducer
dispatch
action type

useReducer — 복잡 상태 전이

여러 setState 호출이 한 묶음으로 일어나거나, 다음 상태가 이전 상태에 의존하면 useReducer. action 을 discriminated union 으로 정의하면 state 전이가 곧 state machine.

📖 핵심 개념

  • (state, action) => state 순수 함수.
  • 호출자는 dispatch(action) — UI 와 비즈니스 로직 분리.
  • 테스트 = reducer 함수만 단위 테스트.

💻 코드 패턴

type State =
  | { kind: 'idle' }
  | { kind: 'loading' }
  | { kind: 'success'; data: User }
  | { kind: 'error'; message: string };

type Action =
  | { type: 'fetch_start' }
  | { type: 'fetch_success'; data: User }
  | { type: 'fetch_error'; message: string }
  | { type: 'reset' };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'fetch_start':   return { kind: 'loading' };
    case 'fetch_success': return { kind: 'success', data: action.data };
    case 'fetch_error':   return { kind: 'error', message: action.message };
    case 'reset':         return { kind: 'idle' };
  }
}

function User({ id }: { id: string }) {
  const [state, dispatch] = useReducer(reducer, { kind: 'idle' });

  useEffect(() => {
    dispatch({ type: 'fetch_start' });
    const ac = new AbortController();
    fetch(`/api/users/${id}`, { signal: ac.signal })
      .then(r => r.json())
      .then(data => dispatch({ type: 'fetch_success', data }))
      .catch(e => { if (e.name !== 'AbortError') dispatch({ type: 'fetch_error', message: e.message }); });
    return () => ac.abort();
  }, [id]);

  switch (state.kind) {
    case 'idle':    return null;
    case 'loading': return <Spinner />;
    case 'success': return <Profile user={state.data} />;
    case 'error':   return <Error msg={state.message} />;
  }
}

🤔 의사결정 기준

상황 useReducer useState
상태 필드 1~2개
다음 상태가 여러 필드 동시 변경 useState 도 가능하지만 reducer 가 명확
상태 머신 (idle/loading/success)
깊은 자식이 dispatch 만 알면 됨 (Context 로 dispatch 만 내려)
외부 라이브러리 (Zustand) 더 나은 경우 글로벌 상태면 외부 store useReducer 는 컴포넌트 단위

안티패턴

  • action 에 함수/promise 넣기: action 은 직렬화 가능 데이터. side effect 는 effect 안에서 dispatch.
  • action.type 을 string union 안 만듦: typo 가능. union 으로.
  • reducer 안에서 fetch / setTimeout: pure 깨짐. effect 가 dispatch.
  • state 직접 mutate (state.foo = 1): React 가 변화 감지 못 함. 항상 새 객체 반환.
  • switch 에 default 없음: 새 action 추가 시 누락 모름. assertNever 패턴.

🤖 LLM 활용 힌트

  • "복잡 상태 전이 → discriminated union state + action, exhaustive switch" 명시.
  • Immer 사용 시 reducer 안에서 mutation OK (immer 가 immutable 변환).

🔗 관련 문서