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:
Antigravity Agent
2026-07-05 00:33:48 +09:00
parent 1cfd3bbb56
commit 9148c358d0
6455 changed files with 1 additions and 86875 deletions
@@ -0,0 +1,183 @@
---
id: react-tanstack-query-advanced
title: TanStack Query 심화 — invalidate / optimistic / prefetch
category: Coding
status: draft
source_trust_level: B
verification_status: conceptual
created_at: 2026-05-09
updated_at: 2026-05-09
tags: [react, tanstack-query, react-query, vibe-coding]
tech_stack: { language: "TypeScript / React", applicable_to: ["Frontend"] }
applied_in: []
aliases: [react-query, useMutation, optimistic update, query invalidation, queryKey]
---
# TanStack Query — Advanced
> Server state 의 표준. **queryKey 는 array + 안정**, mutation 의 `onMutate`/`onError`/`onSettled` 가 optimistic, `setQueryData` + `invalidateQueries` 가 cache 동기화.
## 📖 핵심 개념
- queryKey: 캐시 식별 — 변경 시 새 쿼리.
- Stale: 데이터가 outdated 상태. Refetch trigger.
- Mutation: write — `onMutate` 로 cache 미리 갱신 (optimistic).
- Hydration: SSR / RSC 의 dehydrated state 클라에 주입.
## 💻 코드 패턴
### queryKey 표준화 (factories)
```ts
// queries/users.ts
export const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
list: (filter: UserFilter) => [...userKeys.lists(), filter] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: string) => [...userKeys.details(), id] as const,
};
useQuery({ queryKey: userKeys.detail(id), queryFn: () => api.user.get(id) });
queryClient.invalidateQueries({ queryKey: userKeys.lists() }); // 모든 list invalidate
```
### Optimistic update
```tsx
const qc = useQueryClient();
const mut = useMutation({
mutationFn: (patch: PostPatch) => api.post.update(patch.id, patch),
onMutate: async (patch) => {
// 1. 진행중 query cancel
await qc.cancelQueries({ queryKey: postKeys.detail(patch.id) });
// 2. 이전 값 백업
const prev = qc.getQueryData<Post>(postKeys.detail(patch.id));
// 3. 새 값으로 미리 set
qc.setQueryData<Post>(postKeys.detail(patch.id), old => ({ ...old!, ...patch }));
return { prev }; // context
},
onError: (err, patch, ctx) => {
if (ctx?.prev) qc.setQueryData(postKeys.detail(patch.id), ctx.prev);
},
onSettled: (_, __, patch) => {
qc.invalidateQueries({ queryKey: postKeys.detail(patch.id) });
},
});
```
### Prefetch (Router/hover)
```ts
// route loader
await qc.prefetchQuery({ queryKey: userKeys.detail(id), queryFn: ... });
// hover
<Link to={`/u/${id}`} onMouseEnter={() => qc.prefetchQuery(...)}>...</Link>
```
### Infinite query
```tsx
const q = useInfiniteQuery({
queryKey: postKeys.lists(),
queryFn: ({ pageParam }) => api.post.list({ cursor: pageParam }),
initialPageParam: undefined,
getNextPageParam: (last) => last.nextCursor,
});
const items = q.data?.pages.flatMap(p => p.items) ?? [];
<button onClick={() => q.fetchNextPage()} disabled={!q.hasNextPage}>load more</button>
```
### Suspense + ErrorBoundary
```tsx
<Suspense fallback={<Spinner />}>
<ErrorBoundary fallbackRender={({ error, resetErrorBoundary }) => ...}>
<UserPanel id={id} />
</ErrorBoundary>
</Suspense>
function UserPanel({ id }) {
const { data } = useSuspenseQuery({ queryKey: userKeys.detail(id), queryFn: ... });
return <div>{data.name}</div>; // data 는 항상 정의됨
}
```
### 글로벌 default
```ts
const qc = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000,
gcTime: 5 * 60_000,
retry: (count, err) => count < 2 && !isClientError(err),
refetchOnWindowFocus: 'always',
},
mutations: {
retry: 1,
},
},
});
```
### SSR (Next.js)
```tsx
// server component / loader
export default async function Page() {
const qc = new QueryClient();
await qc.prefetchQuery({ queryKey: userKeys.detail('1'), queryFn: ... });
return (
<HydrationBoundary state={dehydrate(qc)}>
<ClientPage id="1" />
</HydrationBoundary>
);
}
```
### Dependent queries
```tsx
const { data: user } = useQuery({ queryKey: userKeys.detail(id), queryFn: ... });
const { data: posts } = useQuery({
queryKey: postKeys.list({ userId: user?.id }),
queryFn: () => api.post.list({ userId: user!.id }),
enabled: !!user,
});
```
### Selective updates (setQueriesData)
```ts
qc.setQueriesData<User[]>({ queryKey: userKeys.lists() }, (old) =>
old?.map(u => u.id === updated.id ? updated : u)
);
```
## 🤔 의사결정 기준
| 상황 | 권장 |
|---|---|
| Server state | TanStack Query |
| Client-only state | Zustand / useState |
| Form state | RHF |
| Realtime | useQuery + WebSocket invalidate |
| Pagination | useInfiniteQuery |
| 즉시 반응 UI | Optimistic update |
## ❌ 안티패턴
- **queryKey unstable (객체 inline)**: 매 렌더 다른 key — 무한 fetch.
- **Mutation 후 setQueryData 없이 invalidate 만**: refetch 도착까지 빈 화면.
- **Optimistic onError 복원 X**: 실패 시 잘못된 cache.
- **staleTime 0**: 매 마운트 refetch — 과도.
- **Global state 에 server data 복사**: 두 source of truth.
- **enabled false 인데 queryFn 무거움**: ... 그래도 기본 안전.
- **gcTime 너무 길음 (24h)**: 메모리 누적.
## 🤖 LLM 활용 힌트
- queryKey factory + invalidate hierarchy.
- Mutation 4단계 (cancel/backup/set/onSettled invalidate).
- SSR = HydrationBoundary.
## 🔗 관련 문서
- [[React_Suspense_for_Data]]
- [[React_Form_State_Patterns]]
- [[React_Server_Components]]