9148c358d0
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 폴더 제거.
7.7 KiB
7.7 KiB
id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
| id | title | category | status | canonical_id | aliases | duplicate_of | source_trust_level | confidence_score | verification_status | tags | raw_sources | last_reinforced | github_commit | tech_stack | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| wiki-2026-0508-state-management-libraries | State Management Libraries | 10_Wiki/Topics | verified | self |
|
none | A | 0.95 | applied |
|
2026-05-10 | pending |
|
State Management Libraries
매 한 줄
"매 state management 는 component tree 외부의 reactive store 추상화". 2026 기준 React server-side data 는 TanStack Query / RSC, client-only state 는 Zustand (top-down) / Jotai (bottom-up atomic) / Valtio (proxy mutable) 가 mainstream. Redux 는 legacy + 매우 큰 enterprise 만. 매 핵심 결정은 "어떤 abstraction 이 mental model 과 맞는가".
매 핵심
매 4 가지 패러다임
- Top-down store (Zustand, Redux): 단일 store, selector
- Atomic (Jotai, Recoil): 작은 atom 의 graph
- Proxy mutable (Valtio, MobX): mutable object, auto-tracking
- Server-state (TanStack Query, SWR): cache + revalidation
매 server vs client
- 2026 의 truth: 매 대부분의 "state" 는 사실 server data → 매 TanStack Query 로
- 진짜 client state (modal open, form draft, theme) → 매 Zustand / Jotai
매 응용
- Zustand: 매 일반 SPA, mid-size app 의 default.
- Jotai: 매 fine-grained reactivity, derived value graph.
- Valtio: 매 game/canvas, mutable mental model 선호.
- Redux Toolkit: 매 legacy migration, Redux DevTools 의존.
💻 패턴
Zustand store with slice pattern
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";
type AuthSlice = {
user: { id: string; name: string } | null;
login: (u: { id: string; name: string }) => void;
logout: () => void;
};
type CartSlice = {
items: { id: string; qty: number }[];
add: (id: string) => void;
};
export const useStore = create<AuthSlice & CartSlice>()(
devtools(
persist(
immer((set) => ({
user: null,
login: (u) => set((s) => { s.user = u; }),
logout: () => set((s) => { s.user = null; }),
items: [],
add: (id) =>
set((s) => {
const it = s.items.find((i) => i.id === id);
if (it) it.qty += 1;
else s.items.push({ id, qty: 1 });
}),
})),
{ name: "app-store" },
),
),
);
// usage with selector to prevent re-render
const user = useStore((s) => s.user);
Jotai atomic + derived
import { atom, useAtom, useAtomValue } from "jotai";
import { atomWithStorage } from "jotai/utils";
export const themeAtom = atomWithStorage<"light" | "dark">("theme", "light");
export const filterAtom = atom("");
export const itemsAtom = atom<{ id: string; name: string }[]>([]);
export const filteredItemsAtom = atom((get) => {
const f = get(filterAtom).toLowerCase();
return get(itemsAtom).filter((i) => i.name.toLowerCase().includes(f));
});
function Search() {
const [filter, setFilter] = useAtom(filterAtom);
const filtered = useAtomValue(filteredItemsAtom);
return (
<>
<input value={filter} onChange={(e) => setFilter(e.target.value)} />
<ul>{filtered.map((i) => <li key={i.id}>{i.name}</li>)}</ul>
</>
);
}
Valtio proxy
import { proxy, useSnapshot } from "valtio";
export const game = proxy({
player: { x: 0, y: 0, hp: 100 },
enemies: [] as { id: string; x: number; y: number }[],
damage(amount: number) {
game.player.hp = Math.max(0, game.player.hp - amount);
},
});
function HUD() {
const snap = useSnapshot(game);
return <div>HP: {snap.player.hp}</div>;
}
// mutate directly outside React
setInterval(() => {
game.player.x += 1; // 매 자동으로 컴포넌트 re-render
}, 16);
Redux Toolkit (when 필요)
import { createSlice, configureStore } from "@reduxjs/toolkit";
const counter = createSlice({
name: "counter",
initialState: { value: 0 },
reducers: {
inc: (s) => { s.value += 1; },
incBy: (s, a: { payload: number }) => { s.value += a.payload; },
},
});
export const { inc, incBy } = counter.actions;
export const store = configureStore({ reducer: { counter: counter.reducer } });
TanStack Query for server state
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
export function usePosts() {
return useQuery({
queryKey: ["posts"],
queryFn: () => fetch("/api/posts").then((r) => r.json()),
staleTime: 60_000,
});
}
export function useCreatePost() {
const qc = useQueryClient();
return useMutation({
mutationFn: (body: { title: string }) =>
fetch("/api/posts", { method: "POST", body: JSON.stringify(body) }),
onSuccess: () => qc.invalidateQueries({ queryKey: ["posts"] }),
});
}
Zustand + RSC bridge (Next.js 15)
// store-provider.tsx
"use client";
import { createContext, useContext, useRef } from "react";
import { useStore as useZ, type StoreApi } from "zustand";
import { createStore } from "zustand/vanilla";
type State = { count: number; inc: () => void };
const StoreCtx = createContext<StoreApi<State> | null>(null);
export function StoreProvider({ children, initialCount = 0 }: any) {
const ref = useRef<StoreApi<State>>();
if (!ref.current) {
ref.current = createStore<State>((set) => ({
count: initialCount,
inc: () => set((s) => ({ count: s.count + 1 })),
}));
}
return <StoreCtx.Provider value={ref.current}>{children}</StoreCtx.Provider>;
}
export function useAppStore<T>(sel: (s: State) => T): T {
const store = useContext(StoreCtx);
if (!store) throw new Error("StoreProvider missing");
return useZ(store, sel);
}
Subscribing outside React (Zustand)
const unsub = useStore.subscribe(
(s) => s.user,
(user) => console.log("user changed", user),
);
매 결정 기준
| 상황 | Approach |
|---|---|
| Server data (lists, details) | TanStack Query / SWR |
| Mid-size client state, simple | Zustand |
| Fine-grained derived graphs | Jotai |
| Mutable mental model, games | Valtio |
| Legacy / strict Redux DevTools | Redux Toolkit |
| Shared single value (theme, locale) | Context (sufficient) |
기본값: server state → TanStack Query, client state → Zustand. Jotai 는 atom graph 가 도움될 때.
🔗 Graph
- 부모: React · Large_Frontend_Projects
- 변형: Zustand · Jotai · Valtio · Redux Toolkit · MobX · Recoil
- Adjacent: React Server Components — 경계 의식
🤖 LLM 활용
언제: client-only state design, store shape 결정, library 선택. 매 SPA 의 boundary. 언제 X: server data fetch (TanStack Query), 매 single-component local state (useState).
❌ 안티패턴
- Redux for everything: 매 small app 에 boilerplate. 매 Zustand 로 충분.
- Server state in Zustand: cache invalidation 직접 구현 → 매 TanStack Query 사용.
- Atom 폭발: Jotai 에서 모든 변수를 atom 으로 → 매 graph navigation 혼란.
- No selector:
useStore((s) => s)전체 구독 → 모든 변경에 re-render. - Mutating snapshot: Valtio snap 을 직접 mutate → noop or warning.
- Multiple stores for same domain: 매 single source of truth 위배.
🧪 검증 / 중복
- Verified (Zustand/Jotai/Valtio/Redux Toolkit official docs, 2026).
- 신뢰도 A.
🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — state management libraries canonical full content |