docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
---
|
||||
id: react-reducer-usereducer
|
||||
title: useReducer — 복잡 상태 전이
|
||||
category: Coding
|
||||
status: draft
|
||||
source_trust_level: B
|
||||
verification_status: conceptual
|
||||
created_at: 2026-05-09
|
||||
updated_at: 2026-05-09
|
||||
tags: [react, reducer, state-machine, vibe-coding]
|
||||
tech_stack: { language: "TypeScript / React 18+", applicable_to: ["Web", "React Native"] }
|
||||
applied_in: []
|
||||
aliases: [useReducer, dispatch, action type]
|
||||
---
|
||||
|
||||
# useReducer — 복잡 상태 전이
|
||||
|
||||
> 여러 setState 호출이 한 묶음으로 일어나거나, 다음 상태가 이전 상태에 의존하면 useReducer. **action 을 discriminated union 으로 정의**하면 state 전이가 곧 state machine.
|
||||
|
||||
## 📖 핵심 개념
|
||||
- `(state, action) => state` 순수 함수.
|
||||
- 호출자는 dispatch(action) — UI 와 비즈니스 로직 분리.
|
||||
- 테스트 = reducer 함수만 단위 테스트.
|
||||
|
||||
## 💻 코드 패턴
|
||||
|
||||
```ts
|
||||
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 변환).
|
||||
|
||||
## 🔗 관련 문서
|
||||
- [[Tagged_Union_Discriminated_Types]]
|
||||
- [[Pure_Functions_in_Practice]]
|
||||
Reference in New Issue
Block a user