d8a80f6272
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해 끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은 과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업. 도구: Datacollect/scripts/link_reconcile_apply.mjs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
185 lines
6.7 KiB
Markdown
185 lines
6.7 KiB
Markdown
---
|
|
id: wiki-2026-0508-state
|
|
title: State
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Application State, Program State, Stateful, State Management]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [state, programming, architecture, frontend, backend]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: typescript
|
|
framework: agnostic
|
|
---
|
|
|
|
# State
|
|
|
|
## 매 한 줄
|
|
> **"매 state = 매 program 의 매 time 의 매 snapshot"**. 매 변하는 모든 데이터 — 매 UI 의 input value, 매 server 의 user session, 매 game 의 entity transform 까지. 매 state management 가 매 software complexity 의 매 dominant source — Rich Hickey 의 famous "state is hard" quote (Strange Loop 2009).
|
|
|
|
## 매 핵심
|
|
|
|
### 매 분류
|
|
- **Local / component state**: 매 React `useState`, 매 Vue `ref` — 매 single component scope.
|
|
- **Shared / global state**: 매 Redux/Zustand/Pinia/Jotai — 매 multiple components share.
|
|
- **Server state**: 매 React Query/TanStack Query/SWR — 매 server-of-truth 의 매 cache.
|
|
- **URL state**: 매 query params, hash — 매 shareable / bookmarkable.
|
|
- **Persistent state**: 매 localStorage, IndexedDB, DB — 매 across sessions.
|
|
- **Derived state**: 매 computed from base state — 매 NOT stored separately (single source of truth).
|
|
|
|
### 매 state 의 trade-off
|
|
- **매 mutable** vs **매 immutable**: 매 immutability → 매 reasoning easier, 매 time-travel debug 가능, 매 perf cost 일부.
|
|
- **매 local** vs **매 global**: 매 global → 매 sharing easy, 매 coupling explosion.
|
|
- **매 client** vs **매 server**: 매 client → 매 latency 0, 매 inconsistency. 매 server → 매 truth 1, 매 latency.
|
|
- **매 fine-grained** vs **매 coarse**: 매 fine → 매 selective re-render, 매 bookkeeping cost.
|
|
|
|
### 매 modern (2026) frontend stack
|
|
- **Local**: useState/useReducer (React 19), `$state` (Svelte 5 runes), `ref/computed` (Vue 3.5).
|
|
- **Global**: Zustand (most popular React), Jotai (atomic), Pinia (Vue), Redux Toolkit (legacy-heavy).
|
|
- **Server**: TanStack Query 5 (React/Solid/Svelte/Vue), SWR (Vercel), Apollo Client (GraphQL).
|
|
- **URL**: TanStack Router, Next.js useSearchParams, nuqs.
|
|
- **Form**: React Hook Form + Zod (de facto), TanStack Form.
|
|
|
|
## 💻 패턴
|
|
|
|
### Pattern 1: Local state (React)
|
|
```tsx
|
|
import { useState } from "react";
|
|
|
|
function Counter() {
|
|
const [count, setCount] = useState(0);
|
|
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
|
|
}
|
|
```
|
|
|
|
### Pattern 2: Global state (Zustand)
|
|
```typescript
|
|
import { create } from "zustand";
|
|
|
|
interface CartState {
|
|
items: { id: string; qty: number }[];
|
|
add: (id: string) => void;
|
|
remove: (id: string) => void;
|
|
total: () => number;
|
|
}
|
|
|
|
export const useCart = create<CartState>((set, get) => ({
|
|
items: [],
|
|
add: (id) => set(s => {
|
|
const existing = s.items.find(i => i.id === id);
|
|
if (existing) return { items: s.items.map(i => i.id === id ? { ...i, qty: i.qty + 1 } : i) };
|
|
return { items: [...s.items, { id, qty: 1 }] };
|
|
}),
|
|
remove: (id) => set(s => ({ items: s.items.filter(i => i.id !== id) })),
|
|
total: () => get().items.reduce((s, i) => s + i.qty, 0),
|
|
}));
|
|
```
|
|
|
|
### Pattern 3: Server state (TanStack Query)
|
|
```tsx
|
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
|
|
function useUser(id: string) {
|
|
return useQuery({
|
|
queryKey: ["user", id],
|
|
queryFn: () => fetch(`/api/users/${id}`).then(r => r.json()),
|
|
staleTime: 60_000,
|
|
});
|
|
}
|
|
|
|
function useUpdateUser() {
|
|
const qc = useQueryClient();
|
|
return useMutation({
|
|
mutationFn: (u: User) => fetch(`/api/users/${u.id}`, { method: "PUT", body: JSON.stringify(u) }),
|
|
onSuccess: (_, u) => qc.invalidateQueries({ queryKey: ["user", u.id] }),
|
|
});
|
|
}
|
|
```
|
|
|
|
### Pattern 4: URL state (nuqs)
|
|
```tsx
|
|
import { useQueryState, parseAsInteger } from "nuqs";
|
|
|
|
function ProductList() {
|
|
const [page, setPage] = useQueryState("page", parseAsInteger.withDefault(1));
|
|
const [sort, setSort] = useQueryState("sort", { defaultValue: "name" });
|
|
// 매 URL = ?page=2&sort=price → 매 shareable, 매 back-button works.
|
|
}
|
|
```
|
|
|
|
### Pattern 5: Derived state (NEVER duplicate base)
|
|
```tsx
|
|
// 매 BAD — 매 fullName 의 매 별도 state.
|
|
const [first, setFirst] = useState("");
|
|
const [last, setLast] = useState("");
|
|
const [fullName, setFullName] = useState(""); // 매 anti-pattern
|
|
|
|
// 매 GOOD — 매 derive on render.
|
|
const fullName = `${first} ${last}`;
|
|
|
|
// 매 expensive case → useMemo.
|
|
const expensiveResult = useMemo(() => heavyCompute(first, last), [first, last]);
|
|
```
|
|
|
|
### Pattern 6: State machine (XState)
|
|
```typescript
|
|
import { setup } from "xstate";
|
|
|
|
const trafficLight = setup({}).createMachine({
|
|
initial: "red",
|
|
states: {
|
|
red: { on: { TICK: "green" } },
|
|
green: { on: { TICK: "yellow" } },
|
|
yellow: { on: { TICK: "red" } },
|
|
},
|
|
});
|
|
// 매 invalid transition 의 매 compile-time prevention.
|
|
```
|
|
|
|
## 매 결정 기준
|
|
| 상황 | Approach |
|
|
|---|---|
|
|
| 매 component-local UI | useState |
|
|
| 매 2-3 component shared | Lift state up / Context |
|
|
| 매 app-wide global | Zustand / Jotai |
|
|
| 매 server data | TanStack Query (NOT global state) |
|
|
| 매 form | React Hook Form + Zod |
|
|
| 매 URL-bound | nuqs / TanStack Router |
|
|
| 매 complex transitions | XState (state machine) |
|
|
| 매 persistent | Zustand persist middleware / IndexedDB |
|
|
|
|
**기본값**: 매 derive whenever possible. 매 store 만 base state. 매 server state 의 매 global state X (TanStack Query 사용).
|
|
|
|
## 🔗 Graph
|
|
- 부모: [[State Management]] · [[Architecture]]
|
|
- 변형: [[Server State]]
|
|
- 응용: [[React]] · [[Zustand]] · [[XState]]
|
|
- Adjacent: [[Immutability]] · [[State Machine]] · [[Single Source of Truth (SSoT)]]
|
|
|
|
## 🤖 LLM 활용
|
|
**언제**: 매 state shape 의 매 design 추천, 매 derived vs base 의 매 audit.
|
|
**언제 X**: 매 LLM 의 매 over-eager Redux 추천 — 매 modern projects 에서 의 outdated.
|
|
|
|
## ❌ 안티패턴
|
|
- **State duplication**: 매 derivable 의 매 별도 store — 매 sync bugs.
|
|
- **Server state in global store**: 매 cache invalidation 손수 reimplement — 매 TanStack Query 사용.
|
|
- **Prop drilling depth >3**: 매 Context / state lib 의 매 trigger.
|
|
- **Premature global**: 매 1 component scope 의 매 Zustand store — 매 over-engineering.
|
|
- **Mutable update**: 매 `state.items.push(x)` (Redux) — 매 React 의 매 re-render miss.
|
|
|
|
## 🧪 검증 / 중복
|
|
- Verified (React 19 docs, TanStack Query v5 docs, Zustand 4.x, XState v5 docs).
|
|
- 신뢰도 A.
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — State 의 분류, 2026 modern stack, useState/Zustand/TanStack Query/nuqs/XState 패턴 + 기본값 결정표 정리 |
|