chore(brain): ASTRA 성장 자산 동기화 — 기능 인벤토리·growth(약점프로필/학습큐)·일화기억·장기기억·회의록 원문
This commit is contained in:
+250
@@ -0,0 +1,250 @@
|
||||
---
|
||||
id: wiki-2026-0508-state-management-libraries
|
||||
title: State Management Libraries
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [State Management, React State Libraries, Zustand vs Jotai vs Redux]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [state-management, react, zustand, jotai, valtio, redux]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: TypeScript
|
||||
framework: React 19
|
||||
---
|
||||
|
||||
# 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
|
||||
|
||||
### 매 응용
|
||||
1. Zustand: 매 일반 SPA, mid-size app 의 default.
|
||||
2. Jotai: 매 fine-grained reactivity, derived value graph.
|
||||
3. Valtio: 매 game/canvas, mutable mental model 선호.
|
||||
4. Redux Toolkit: 매 legacy migration, Redux DevTools 의존.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Zustand store with slice pattern
|
||||
```typescript
|
||||
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
|
||||
```typescript
|
||||
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
|
||||
```typescript
|
||||
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 필요)
|
||||
```typescript
|
||||
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
|
||||
```typescript
|
||||
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)
|
||||
```typescript
|
||||
// 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)
|
||||
```typescript
|
||||
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|Frontend Architecture]]
|
||||
- 변형: [[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 |
|
||||
Reference in New Issue
Block a user