Files
2nd/10_Wiki/Topics/Frontend/State Management Libraries.md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24:15 +09:00

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
State Management
React State Libraries
Zustand vs Jotai vs Redux
none A 0.95 applied
state-management
react
zustand
jotai
valtio
redux
2026-05-10 pending
language framework
TypeScript 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

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

🤖 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