本文へ移動
cccskills
無料GitHub で公開

state-management-expert

Expert guide for modern client-side state management: Zustand, Jotai, Valtio, TanStack Store, Redux Toolkit, and server state patterns with TanStack Query / Panduan ahli untuk manajemen state client-side modern: Zustand, Jotai, Valtio, TanStack Store, Redux Toolkit, dan pola server state dengan TanStack Query.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md10.1 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

State Management Expert (Modern React Edition)

English | Bahasa Indonesia


<a name="english"></a>

English

Orchestration & Integration

Connects and orchestrates with relevant domain skills like brainstorming, zero-to-prod-orchestrator, and session-memory-manager to ensure cohesive execution.

Description

Expert guide for selecting and implementing the right state management solution for React and Next.js applications. Covers Zustand 5, Jotai 2, Valtio, TanStack Store, and Redux Toolkit 2, with clear guidance on when to use each, proper separation of server state (TanStack Query) from client state, and advanced patterns like slices, persistence, and devtools integration.

Trigger Conditions

  • Choosing a state management library for a new React/Next.js project.
  • Refactoring prop drilling or complex Context API usage.
  • Implementing global UI state (modals, drawers, theme, auth session).
  • Managing complex form state across multiple steps.
  • Implementing undo/redo, optimistic updates, or derived state.
  • Migrating from Redux to a lighter alternative.

State Category Separation (Critical First Step)

Before choosing a library, categorize your state:

CategoryDescriptionSolution
Server StateData from APIs, databasesTanStack Query / SWR
URL StateRoute params, search filtersuseSearchParams, nuqs
Form StateInput values, validation errorsReact Hook Form + Zod
UI/Local StateModals, drawers, togglesuseState / useReducer
Global Client StateTheme, auth, shopping cartZustand / Jotai
Cross-tab StateSync across browser tabsZustand + BroadcastChannel

Rule: Do NOT store server data in client state. Let TanStack Query own all async data.


Library Selection Guide

CriteriaZustand 5Jotai 2ValtioRedux Toolkit
Mental ModelSingle store, actionsAtomic, bottom-upProxy-based, mutableFlux, reducers
Bundle Size~1KB~3KB~3KB~15KB+
DevToolsRedux DevToolsJotai DevToolsRedux DevToolsBuilt-in
AsyncManual or middlewareatomWithQuerysnapshotcreateAsyncThunk
Best ForGeneral global stateAtomic derived stateSimple mutable stateLarge teams, strict patterns

Recommendation: Use Zustand as the default. Use Jotai for fine-grained reactive atoms. Use Redux Toolkit only for large enterprise teams with strict conventions.


Zustand 5 — Best Practices

Basic Store with TypeScript

// stores/ui.store.ts
import { create } from 'zustand';
import { devtools, persist, subscribeWithSelector } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';

interface UiState {
  theme: 'light' | 'dark' | 'system';
  sidebarOpen: boolean;
  activeModal: string | null;
  setTheme: (theme: UiState['theme']) => void;
  toggleSidebar: () => void;
  openModal: (modalId: string) => void;
  closeModal: () => void;
}

export const useUiStore = create<UiState>()(
  devtools(
    persist(
      subscribeWithSelector(
        immer((set) => ({
          theme: 'system',
          sidebarOpen: true,
          activeModal: null,
          setTheme: (theme) => set((state) => { state.theme = theme; }),
          toggleSidebar: () => set((state) => { state.sidebarOpen = !state.sidebarOpen; }),
          openModal: (modalId) => set((state) => { state.activeModal = modalId; }),
          closeModal: () => set((state) => { state.activeModal = null; }),
        }))
      ),
      { name: 'ui-store', partialize: (s) => ({ theme: s.theme }) }
    ),
    { name: 'UiStore' }
  )
);

Slice Pattern for Large Stores

// Pattern: separate slices, combine into one store
import { StateCreator } from 'zustand';

interface AuthSlice {
  user: User | null;
  isAuthenticated: boolean;
  login: (user: User) => void;
  logout: () => void;
}

interface CartSlice {
  items: CartItem[];
  addItem: (item: CartItem) => void;
  removeItem: (id: string) => void;
  total: () => number;
}

type AppStore = AuthSlice & CartSlice;

const createAuthSlice: StateCreator<AppStore, [], [], AuthSlice> = (set) => ({
  user: null,
  isAuthenticated: false,
  login: (user) => set({ user, isAuthenticated: true }),
  logout: () => set({ user: null, isAuthenticated: false }),
});

const createCartSlice: StateCreator<AppStore, [], [], CartSlice> = (set, get) => ({
  items: [],
  addItem: (item) => set((s) => ({ items: [...s.items, item] })),
  removeItem: (id) => set((s) => ({ items: s.items.filter((i) => i.id !== id) })),
  total: () => get().items.reduce((sum, item) => sum + item.price * item.qty, 0),
});

export const useAppStore = create<AppStore>()(
  devtools((...args) => ({
    ...createAuthSlice(...args),
    ...createCartSlice(...args),
  }))
);

Selective Subscriptions (Prevent Unnecessary Rerenders)

// Only re-render when `theme` changes, not the entire store
const theme = useUiStore((s) => s.theme);
const isModalOpen = useUiStore((s) => s.activeModal === 'confirm-delete');

// Subscribe outside React (side effects, non-component code)
useUiStore.subscribe(
  (s) => s.theme,
  (theme) => document.documentElement.dataset.theme = theme,
  { fireImmediately: true }
);

Jotai 2 — Atomic State Patterns

// atoms/user.atoms.ts
import { atom, loadable } from 'jotai';
import { atomWithStorage, atomWithReset } from 'jotai/utils';

// Primitive atom
export const themeAtom = atomWithStorage<'light' | 'dark'>('theme', 'light');

// Derived (read-only) atom
export const isDarkAtom = atom((get) => get(themeAtom) === 'dark');

// Async atom with loadable for Suspense-free usage
export const userAtom = atom(async () => {
  const res = await fetch('/api/me');
  if (!res.ok) throw new Error('Failed to fetch user');
  return res.json() as Promise<User>;
});

export const loadableUserAtom = loadable(userAtom);

// In component:
function UserWidget() {
  const loadableUser = useAtomValue(loadableUserAtom);
  if (loadableUser.state === 'loading') return <Spinner />;
  if (loadableUser.state === 'hasError') return <Error />;
  return <div>{loadableUser.data.name}</div>;
}

Redux Toolkit 2 — Modern Patterns

// features/cart/cartSlice.ts
import { createSlice, PayloadAction, createSelector } from '@reduxjs/toolkit';

interface CartState {
  items: CartItem[];
  status: 'idle' | 'loading' | 'failed';
}

const cartSlice = createSlice({
  name: 'cart',
  initialState: { items: [], status: 'idle' } as CartState,
  reducers: {
    addItem(state, action: PayloadAction<CartItem>) {
      state.items.push(action.payload); // Immer handles immutability
    },
    removeItem(state, action: PayloadAction<string>) {
      state.items = state.items.filter((i) => i.id !== action.payload);
    },
  },
});

// Memoized selector
export const selectCartTotal = createSelector(
  (state: RootState) => state.cart.items,
  (items) => items.reduce((sum, i) => sum + i.price * i.qty, 0)
);

export const { addItem, removeItem } = cartSlice.actions;
export default cartSlice.reducer;

Integration with Next.js App Router

  • Server Components: No client state. Fetch directly.
  • Client Components: Use Zustand/Jotai wrapped in providers.
  • Hydration: Initialize Zustand store from server-fetched data using useHydrateAtoms (Jotai) or a HydrationBoundary pattern.
// providers/store-provider.tsx (App Router pattern)
'use client';
import { createStore, Provider } from 'jotai';
import { useRef } from 'react';

type Props = { children: React.ReactNode; initialUser?: User };

export function StoreProvider({ children, initialUser }: Props) {
  const store = useRef(createStore());
  if (initialUser) store.current.set(userAtom, initialUser);
  return <Provider store={store.current}>{children}</Provider>;
}

<a name="bahasa-indonesia"></a>

Bahasa Indonesia

Integrasi Orkestrasi

Terhubung dan mengorkestrasi skill domain yang relevan seperti brainstorming, zero-to-prod-orchestrator, dan session-memory-manager untuk memastikan eksekusi yang kohesif.

Deskripsi

Panduan ahli untuk memilih dan mengimplementasikan solusi manajemen state yang tepat untuk aplikasi React dan Next.js. Mencakup Zustand 5, Jotai 2, Valtio, dan Redux Toolkit 2, dengan panduan pemilihan yang jelas, pemisahan server state (TanStack Query) dari client state, dan pola lanjutan seperti slices, persistensi, dan integrasi devtools.

Kondisi Pemicu

  • Memilih library state management untuk proyek React/Next.js baru.
  • Refaktor prop drilling atau penggunaan Context API yang rumit.
  • Mengimplementasikan global UI state (modal, drawer, tema, sesi auth).
  • Mengelola state form kompleks di beberapa langkah.
  • Mengimplementasikan undo/redo, optimistic update, atau derived state.
  • Migrasi dari Redux ke alternatif yang lebih ringan.

Prinsip Utama

  • Pisahkan server state dari client state: Server state (data dari API) dikelola TanStack Query. Client state (UI, preferensi) dikelola Zustand/Jotai.
  • Gunakan Zustand sebagai default untuk state global umum.
  • Gunakan Jotai untuk state atomik yang sangat granular dan reaktif.
  • Hindari menyimpan data server di client state — ini adalah sumber bug terbesar di aplikasi React.
  • Selective subscription: Selalu gunakan selector untuk menghindari re-render yang tidak perlu.
  • DevTools: Selalu integrasikan devtools di development untuk debugging yang efektif.

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Expert guide for automated and manual Web Accessibility (a11y) testing — axe-core, Pa11y, Playwright a11y, screen reader testing, and WCAG 2.2 Level AA/AAA compliance / Panduan ahli pengujian aksesibilitas web.

日本語の概要は準備中です。原文の説明を表示しています。

roedyrustam/vibes-plug752026年10月9日 更新

Expert guide for intelligent model cascading and routing — complexity-scored task routing from Flash/Haiku to Sonnet/Opus/Astra, dynamic escalation with quality gates, 40-60% token cost reduction while maintaining output quality / Panduan ahli untuk kaskade dan routing model cerdas — routing tugas berbasis skor kompleksitas dari Flash/Haiku ke Sonnet/Opus/Astra, eskalasi dinamis dengan gerbang kualitas, pengurangan biaya token 40-60% dengan kualitas output terjaga.

日本語の概要は準備中です。原文の説明を表示しています。

roedyrustam/vibes-plug752026年10月9日 更新

Expert guide for Affective Computing, emotional AI, and real-time sentiment analysis through native multimodal tokens (voice intonation and facial micro-expressions) / Panduan ahli komputasi afektif, AI emosional, dan analisis sentimen real-time melalui token multimodal native.

日本語の概要は準備中です。原文の説明を表示しています。

roedyrustam/vibes-plug752026年10月9日 更新

Expert guide for AI-assisted coding workflows — agentic code generation, multi-agent code swarms, self-healing CI/CD, automated PR review, spec-to-code pipelines, codebase knowledge graphs, and human-in-the-loop approval gates / Panduan ahli untuk workflow pengkodean berbasis AI — generasi kode agentic, code swarm multi-agen, CI/CD self-healing, review PR otomatis, pipeline spec-to-code, knowledge graph codebase, dan gate persetujuan human-in-the-loop.

日本語の概要は準備中です。原文の説明を表示しています。

roedyrustam/vibes-plug752026年10月9日 更新

Expert guide for long-term episodic memory integration (Mem0 v2, Letta/MemGPT, Zep v2), memory tier architecture, pgvector HNSW storage, and unified context management for autonomous AI agents / Panduan ahli untuk integrasi memori episodik jangka panjang (Mem0 v2, Letta/MemGPT, Zep v2), arsitektur tier memori, penyimpanan pgvector HNSW, dan manajemen konteks terpadu untuk agen AI otonom.

日本語の概要は準備中です。原文の説明を表示しています。

roedyrustam/vibes-plug752026年10月9日 更新

Expert guide for designing Machine-to-Machine (M2M) micro-economies, autonomous agent wallets, and swarm budget allocation / Panduan ahli merancang ekonomi mikro antar-agen (M2M), dompet agen otonom, dan alokasi anggaran swarm.

日本語の概要は準備中です。原文の説明を表示しています。

roedyrustam/vibes-plug752026年10月9日 更新

roedyrustam のスキルをすべて見る

このスキルの問題を報告する