AgentStack
Browse Sign in
Browse Why AgentStack Sell Docs
Sign in
SKILL verified MIT Self-run

Zustand Tanstack

skill-ggombee-code-forge-zustand-tanstack · by ggombee

Zustand + TanStack Query 상태 관리 패턴. store 생성, devtools, 서버 상태 연동, 디렉토리 구조.

No reviews yet
0 installs
10 views
0.0% view→install

Install

$ agentstack add skill-ggombee-code-forge-zustand-tanstack

✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

View the full security report →

Verified badge

Passed review? Show it. Paste this badge into your README, it links to the public security report.

AgentStack Verified badge Links to your public security report.
[![AgentStack Verified](https://agentstack.voostack.com/badges/verified.svg)](https://agentstack.voostack.com/security/report/skill-ggombee-code-forge-zustand-tanstack)

Reliability & compatibility

Security review passed
0 installs to date
no reviews yet
1mo ago

Declared compatibility

Claude CodeClaude Desktop

Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.

Preview Execution monitoring

We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.

How agent discovery & health will work →
Are you the author of Zustand Tanstack? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Zustand + TanStack Query 상태 관리 컨벤션


상태 분리 원칙

| 상태 유형 | 도구 | 예시 | |-----------|------|------| | 서버 상태 | TanStack Query | 주문 목록, 사용자 정보 | | 전역 클라이언트 상태 | Zustand | 선택된 탭, 사이드바 열림 여부 | | 폼 상태 | React Hook Form | 입력값, 유효성 검사 | | 로컬 UI 상태 | useState | 모달 열림/닫힘 |


디렉토리 구조

store/
├── useAuthStore.ts       # 인증 상태
├── useUIStore.ts         # UI 전역 상태
└── useFilterStore.ts     # 필터/검색 상태

queries/
├── order/
│   ├── index.ts          # useOrderQuery, useOrderMutation
│   └── queryKeys.ts      # 쿼리 키 팩토리
└── user/
    ├── index.ts
    └── queryKeys.ts

Zustand Store 생성

기본 패턴

// store/useAuthStore.ts
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

interface User {
  id: string;
  name: string;
  email: string;
}

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

export const useAuthStore = create()(
  devtools(
    persist(
      (set) => ({
        user: null,
        isAuthenticated: false,
        login: (user) => set({ user, isAuthenticated: true }, false, 'login'),
        logout: () => set({ user: null, isAuthenticated: false }, false, 'logout'),
      }),
      {
        name: 'auth-storage', // localStorage key
        partialize: (state) => ({ user: state.user }), // 저장할 필드만 선택
      },
    ),
    { name: 'AuthStore' }, // DevTools 이름
  ),
);

UI 상태 store

// store/useUIStore.ts
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

interface UIState {
  isSidebarOpen: boolean;
  activeTab: string;
  // Actions
  toggleSidebar: () => void;
  setActiveTab: (tab: string) => void;
}

export const useUIStore = create()(
  devtools(
    (set) => ({
      isSidebarOpen: true,
      activeTab: 'overview',
      toggleSidebar: () =>
        set((state) => ({ isSidebarOpen: !state.isSidebarOpen }), false, 'toggleSidebar'),
      setActiveTab: (tab) =>
        set({ activeTab: tab }, false, 'setActiveTab'),
    }),
    { name: 'UIStore' },
  ),
);

Zustand 사용 패턴

// ✅ 좋은 예: selector로 필요한 상태만 구독
function Header() {
  const user = useAuthStore((state) => state.user);
  const logout = useAuthStore((state) => state.logout);

  return {user?.name} 로그아웃;
}

// ❌ 나쁜 예: 전체 state 구독 (불필요한 리렌더링 발생)
function Header() {
  const { user, logout } = useAuthStore();
}
// ✅ 여러 값을 한번에 구독할 때 (shallow 비교)
import { useShallow } from 'zustand/react/shallow';

function FilterPanel() {
  const { status, dateRange, setStatus } = useFilterStore(
    useShallow((state) => ({
      status: state.status,
      dateRange: state.dateRange,
      setStatus: state.setStatus,
    })),
  );
}

TanStack Query 연동

쿼리 키 팩토리

// queries/order/queryKeys.ts
export const orderKeys = {
  all: ['orders'] as const,
  lists: () => [...orderKeys.all, 'list'] as const,
  list: (filters: OrderFilters) => [...orderKeys.lists(), filters] as const,
  details: () => [...orderKeys.all, 'detail'] as const,
  detail: (id: string) => [...orderKeys.details(), id] as const,
};

쿼리/뮤테이션 훅

// queries/order/index.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { orderKeys } from './queryKeys';
import { fetchOrders, fetchOrder, createOrder, updateOrder } from '@/services/order';

export function useOrderListQuery(filters: OrderFilters) {
  return useQuery({
    queryKey: orderKeys.list(filters),
    queryFn: () => fetchOrders(filters),
    staleTime: 5 * 60 * 1000, // 5분
  });
}

export function useOrderDetailQuery(id: string) {
  return useQuery({
    queryKey: orderKeys.detail(id),
    queryFn: () => fetchOrder(id),
    enabled: !!id, // id가 있을 때만 실행
  });
}

export function useCreateOrderMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: createOrder,
    onSuccess: () => {
      // 목록 캐시 무효화
      queryClient.invalidateQueries({ queryKey: orderKeys.lists() });
    },
  });
}

Zustand + TanStack Query 연동

// Zustand 필터 상태 + TanStack Query 서버 상태 조합
function OrderListPage() {
  // 클라이언트 상태 (Zustand)
  const filters = useFilterStore(useShallow((s) => ({
    status: s.status,
    dateRange: s.dateRange,
  })));

  // 서버 상태 (TanStack Query)
  const { data, isLoading } = useOrderListQuery(filters);

  return ;
}

QueryClient 설정

// src/main.tsx 또는 providers/QueryProvider.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60 * 1000, // 1분
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
});

function Providers({ children }: { children: React.ReactNode }) {
  return (
    
      {children}
      
    
  );
}

체크리스트

  • [ ] 서버 상태는 TanStack Query, 클라이언트 상태는 Zustand 사용?
  • [ ] store에 devtools 미들웨어 적용?
  • [ ] selector로 필요한 상태만 구독?
  • [ ] 여러 값 구독 시 useShallow 사용?
  • [ ] 쿼리 키는 queryKeys 팩토리로 관리?
  • [ ] mutation 후 관련 쿼리 invalidateQueries 처리?

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet, be the first.

Versions

  • v0.1.0 Imported from the upstream source.