[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,217 @@
|
||||
id: wiki-2026-0508-custom-hooks-patterns
|
||||
title: Custom Hooks Patterns
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [FE-REACT-CUSTOM-HOOK-001]
|
||||
aliases: [React Custom Hooks, useXxx Patterns]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [react, Frontend, custom-hooks, dry, refactoring, separation-of-concerns, business-Logic]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [react, hooks, patterns]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript
|
||||
framework: React 19
|
||||
---
|
||||
|
||||
# Custom Hooks Patterns (커스텀 훅 패턴)
|
||||
# Custom Hooks Patterns
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "UI 렌더링과 비즈니스 로직을 날카롭게 분리하고, 반복되는 로직을 독립적인 함수로 캡슐화하여 컴포넌트의 가독성과 테스트 가능성을 극대화하라" — React에서 로직 재사용의 가장 강력하고 유연한 표준 방식.
|
||||
## 매 한 줄
|
||||
> **"매 custom hook = stateful logic 의 재사용 unit, JSX 의 X."**. React 19 (2024) `use()` + Server Components 시대에는 custom hook이 매 client-side state machine + side effect orchestration 의 primary abstraction. 매 naming은 `useXxx` — 매 ESLint react-hooks rule 의 enforce.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Logic Decoupling and Reusable Abstraction" — 데이터 패칭, 상태 관리, 이벤트 리스너 등록 등의 횡단 관심사를 컴포넌트 밖으로 추출하여 `useX`라는 이름의 커스텀 인터페이스로 추상화하는 패턴.
|
||||
- **주요 적용 사례:**
|
||||
- **Data Fetching:** `useFetch`, `useQuery` 등을 통해 로딩/에러 상태와 데이터 처리 로직 공유.
|
||||
- **Form [[Management|Management]]:** `useForm`을 통해 입력값 바인딩 및 유효성 검사 로직 재사용.
|
||||
- **Global [[State|State]] / [[Storage|Storage]]:** `useLocalStorage`, `useAuth` 등을 통해 외부 상태와의 동기화.
|
||||
- **설계 원칙:**
|
||||
- **Naming:** 반드시 `use` 접두사로 시작하여 훅임을 명시.
|
||||
- **Co-location:** 특정 도메인에 국한된 훅은 해당 도메인 폴더에, 범용 훅은 `src/hooks`에 배치.
|
||||
- **의의:** 중복 코드를 제거(DRY)하고, 복잡한 컴포넌트의 인지적 부하를 줄여 유지보수 비용을 획기적으로 낮춤.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 과거에는 로직 재사용을 위해 고차 컴포넌트(HOC)나 [[Render Props|Render Props]]를 사용했으나, 훅 도입 이후 이러한 방식은 'Wrapper Hell'을 유발하는 지양해야 할 정책으로 간주됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 30라인 이상의 비즈니스 로직을 포함하는 컴포넌트 개발 시 반드시 커스텀 훅으로의 분리를 검토하도록 강제하며, 훅 내부에서 사이드 이펙트(Effect) 발생 시 명확한 클린업 로직을 포함하는 것을 정책화함.
|
||||
### 매 규칙 (Rules of Hooks)
|
||||
- Top-level 만 호출 — 매 conditional / loop X.
|
||||
- React function / 매 다른 hook 안에서 만 — 매 일반 function X.
|
||||
- Naming `useXxx` — 매 lint 가 의존.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[React-Hooks|React-Hooks]], [[Dry-Principle|DRY-Principle]], [[Clean-Code-Principles|Clean-Code-Principles]], [[Component-Composition|Component-Composition]]
|
||||
- **Raw Source:** 00_Raw/Custom Hooks.md
|
||||
### 매 composition
|
||||
- Hook = 매 다른 hook 의 조합 — `useMutation` ← `useState` + `useCallback` + `useRef`.
|
||||
- 매 stateful logic 의 분리 + 매 testable 단위.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Data fetching — `useQuery`, `useSWR`.
|
||||
2. DOM observation — `useIntersectionObserver`, `useResizeObserver`.
|
||||
3. State machines — `useToggle`, `useReducer` wrapper.
|
||||
4. Browser API — `useLocalStorage`, `useMediaQuery`, `useGeolocation`.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 1. useToggle (state primitive)
|
||||
```typescript
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
export function useToggle(initial = false) {
|
||||
const [on, setOn] = useState(initial);
|
||||
const toggle = useCallback(() => setOn((v) => !v), []);
|
||||
const setOnTrue = useCallback(() => setOn(true), []);
|
||||
const setOnFalse = useCallback(() => setOn(false), []);
|
||||
return { on, toggle, setOnTrue, setOnFalse };
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 2. useDebouncedValue
|
||||
```typescript
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
export function useDebouncedValue<T>(value: T, delayMs = 300): T {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
useEffect(() => {
|
||||
const id = setTimeout(() => setDebounced(value), delayMs);
|
||||
return () => clearTimeout(id);
|
||||
}, [value, delayMs]);
|
||||
return debounced;
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 3. useEventListener (typed)
|
||||
```typescript
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
export function useEventListener<K extends keyof WindowEventMap>(
|
||||
type: K,
|
||||
handler: (e: WindowEventMap[K]) => void,
|
||||
target: Window | HTMLElement = window,
|
||||
) {
|
||||
const handlerRef = useRef(handler);
|
||||
useEffect(() => { handlerRef.current = handler; });
|
||||
useEffect(() => {
|
||||
const listener = (e: Event) => handlerRef.current(e as WindowEventMap[K]);
|
||||
target.addEventListener(type, listener);
|
||||
return () => target.removeEventListener(type, listener);
|
||||
}, [type, target]);
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 4. useIntersectionObserver
|
||||
```typescript
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
export function useIntersectionObserver<T extends Element>(
|
||||
options: IntersectionObserverInit = {},
|
||||
) {
|
||||
const ref = useRef<T>(null);
|
||||
const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);
|
||||
useEffect(() => {
|
||||
if (!ref.current) return;
|
||||
const obs = new IntersectionObserver(([e]) => setEntry(e), options);
|
||||
obs.observe(ref.current);
|
||||
return () => obs.disconnect();
|
||||
}, [options.root, options.rootMargin, options.threshold]);
|
||||
return { ref, entry, isVisible: entry?.isIntersecting ?? false };
|
||||
}
|
||||
```
|
||||
|
||||
### 5. useLocalStorage (with sync)
|
||||
```typescript
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useLocalStorage<T>(key: string, initial: T) {
|
||||
const [value, setValue] = useState<T>(() => {
|
||||
const raw = localStorage.getItem(key);
|
||||
return raw ? (JSON.parse(raw) as T) : initial;
|
||||
});
|
||||
useEffect(() => {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
}, [key, value]);
|
||||
useEffect(() => {
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key === key && e.newValue) setValue(JSON.parse(e.newValue));
|
||||
};
|
||||
window.addEventListener('storage', onStorage);
|
||||
return () => window.removeEventListener('storage', onStorage);
|
||||
}, [key]);
|
||||
return [value, setValue] as const;
|
||||
}
|
||||
```
|
||||
|
||||
### 6. useFetch (with AbortController)
|
||||
```typescript
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useFetch<T>(url: string) {
|
||||
const [state, setState] = useState<{ data?: T; error?: Error; loading: boolean }>({ loading: true });
|
||||
useEffect(() => {
|
||||
const ac = new AbortController();
|
||||
setState({ loading: true });
|
||||
fetch(url, { signal: ac.signal })
|
||||
.then((r) => r.json())
|
||||
.then((data: T) => setState({ data, loading: false }))
|
||||
.catch((error: Error) => {
|
||||
if (error.name !== 'AbortError') setState({ error, loading: false });
|
||||
});
|
||||
return () => ac.abort();
|
||||
}, [url]);
|
||||
return state;
|
||||
}
|
||||
```
|
||||
|
||||
### 7. useReducer composite (state machine)
|
||||
```typescript
|
||||
import { useReducer } from 'react';
|
||||
|
||||
type State = { status: 'idle' | 'loading' | 'success' | 'error'; data?: unknown; error?: Error };
|
||||
type Action = { type: 'fetch' } | { type: 'success'; data: unknown } | { type: 'error'; error: Error };
|
||||
|
||||
const reducer = (s: State, a: Action): State => {
|
||||
switch (a.type) {
|
||||
case 'fetch': return { status: 'loading' };
|
||||
case 'success': return { status: 'success', data: a.data };
|
||||
case 'error': return { status: 'error', error: a.error };
|
||||
}
|
||||
};
|
||||
|
||||
export const useAsync = () => useReducer(reducer, { status: 'idle' });
|
||||
```
|
||||
|
||||
### 8. React 19 `use()` for promises
|
||||
```typescript
|
||||
import { use, Suspense } from 'react';
|
||||
|
||||
function Profile({ promise }: { promise: Promise<User> }) {
|
||||
const user = use(promise); // suspends until resolved
|
||||
return <h1>{user.name}</h1>;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Local boolean | `useToggle`. |
|
||||
| Server data | `useQuery` (TanStack Query) — 매 wheel 재발명 X. |
|
||||
| 매 cross-tab sync | `useLocalStorage` + `storage` event. |
|
||||
| Async resource | React 19 `use()` + Suspense. |
|
||||
| 복잡 state | `useReducer` 매 state machine. |
|
||||
| 매 DOM measurement | `useResizeObserver`, `useIntersectionObserver`. |
|
||||
|
||||
**기본값**: 매 TanStack Query / Zustand 의 use — custom hook은 매 truly specific logic 만.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[React]] · [[Hooks]]
|
||||
- 변형: [[Vue Composables]] · [[Solid Primitives]]
|
||||
- 응용: [[Component Library]] · [[Design System]]
|
||||
- Adjacent: [[useEffect]] · [[State Management]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 hook scaffolding, TS generic 작성, 매 cleanup logic.
|
||||
**언제 X**: 매 stale-closure / dep array 미세 bug — 매 manual review 필요.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Conditional hook call**: 매 `if (x) useFoo()` — 매 lint error.
|
||||
- **Stale closure in setInterval**: 매 ref pattern 또는 functional setState 사용.
|
||||
- **Effect for derived state**: 매 `useMemo` 또는 render 중 계산 — `useEffect` X.
|
||||
- **No cleanup**: 매 listener / subscription 미해제 — leak.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (react.dev, React 19 release notes).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — React 19 hook patterns + use() |
|
||||
|
||||
Reference in New Issue
Block a user