본문으로 건너뛰기
cccskills
무료GitHub에 공개

tanstack-query

TanStack Query (React Query) v5 best practices for data fetching, caching, mutations, and server state management. Use when building data-driven React applications, setting up query configurations, implementing mutations/optimistic updates, configuring caching strategies, integrating with SSR, or fixing v4→v5 migration errors.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(13)

  • SKILL.md8.8 KB
  • rules/cache-configuration.md2.8 KB
  • rules/cache-invalidation.md2.6 KB
  • rules/err-error-handling.md3.0 KB
  • rules/inf-infinite-queries.md3.0 KB
  • rules/mut-basics.md3.0 KB
  • rules/mut-optimistic-updates.md3.1 KB
  • rules/offline-support.md2.7 KB
  • rules/parallel-queries.md2.7 KB
  • rules/perf-optimization.md3.7 KB
  • rules/pf-prefetching.md2.2 KB
  • rules/qk-query-keys.md3.6 KB
  • rules/ssr-hydration.md3.7 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

TanStack Query v5

Version: @tanstack/react-query@5.90.x Requires: React 18.0+, TypeScript 4.7+

v5 New Features

  • useMutationState — cross-component mutation tracking without prop drilling
  • Simplified optimistic updates — via variables from pending mutations, no cache manipulation needed
  • throwOnError — renamed from useErrorBoundary
  • networkMode — offline/PWA support (online | always | offlineFirst)
  • useQueries with combine — merge parallel query results into single object
  • infiniteQueryOptions — type-safe factory for infinite queries (parallel to queryOptions)
  • maxPages — limit pages in cache for infinite queries (requires bi-directional pagination)
  • Mutation callback signature change (v5.89+) — onError/onSuccess/onSettled now receive 4 params (added onMutateResult)

Quick Setup

npm install @tanstack/react-query@latest @tanstack/react-query-devtools@latest
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 min
      gcTime: 1000 * 60 * 60,   // 1 hour
      refetchOnWindowFocus: false,
    },
  },
})

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <YourApp />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  )
}

Unified Devtools (Recommended with Multiple TanStack Libraries)

If using Query + Router (or other TanStack libraries), use the unified TanStackDevtools shell instead of individual devtools components:

npm install -D @tanstack/react-devtools
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtoolsPanel } from '@tanstack/react-query-devtools'
import { TanStackDevtools } from '@tanstack/react-devtools'

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <YourApp />
      <TanStackDevtools
        config={{ position: 'bottom-right' }}
        plugins={[
          { name: 'TanStack Query', render: <ReactQueryDevtoolsPanel /> },
          // Add more plugins: Router, etc.
        ]}
      />
    </QueryClientProvider>
  )
}

Use *Panel variants (ReactQueryDevtoolsPanel, TanStackRouterDevtoolsPanel) when embedding inside TanStackDevtools.

import { useQuery, useMutation, useQueryClient, queryOptions } from '@tanstack/react-query'

const todosQueryOptions = queryOptions({
  queryKey: ['todos'],
  queryFn: async () => {
    const res = await fetch('/api/todos')
    if (!res.ok) throw new Error('Failed to fetch')
    return res.json()
  },
})

function useTodos() {
  return useQuery(todosQueryOptions)
}

function useAddTodo() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (newTodo: { title: string }) => {
      const res = await fetch('/api/todos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newTodo),
      })
      if (!res.ok) throw new Error('Failed to add')
      return res.json()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
  })
}

Rule Categories

PriorityCategoryRule FileImpact
CRITICALQuery Keysrules/qk-query-keys.mdPrevents cache bugs and data inconsistencies
CRITICALCachingrules/cache-configuration.mdOptimizes performance and data freshness
HIGHInvalidationrules/cache-invalidation.mdEnsures stale data is properly refreshed
HIGHMutationsrules/mut-basics.mdEnsures data integrity after writes
HIGHOptimistic Updatesrules/mut-optimistic-updates.mdResponsive UI during mutations
HIGHError Handlingrules/err-error-handling.mdPrevents poor user experiences
MEDIUMPrefetchingrules/pf-prefetching.mdImproves perceived performance
MEDIUMInfinite Queriesrules/inf-infinite-queries.mdPrevents pagination bugs
MEDIUMSSR/Hydrationrules/ssr-hydration.mdEnables proper server rendering
MEDIUMParallel Queriesrules/parallel-queries.mdDynamic parallel fetching
LOWPerformancerules/perf-optimization.mdReduces unnecessary re-renders
LOWOffline Supportrules/offline-support.mdEnables offline-first patterns

Critical Rules

Always Do

  • Object syntax for all hooks: useQuery({ queryKey, queryFn, ...options })
  • Array query keys: ['todos'], ['todos', id], ['todos', { filter }]
  • Throw errors in queryFn: if (!res.ok) throw new Error('Failed')
  • isPending for initial loading: if (isPending) return <Loading />
  • Invalidate after mutations: onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] })
  • queryOptions factory: reuse across useQuery, useSuspenseQuery, prefetchQuery
  • gcTime (not cacheTime): renamed in v5

Never Do

  • v4 array/function syntax: useQuery(['todos'], fetchTodos) — removed in v5
  • Query callbacks: onSuccess/onError/onSettled removed from queries (still work in mutations) — use useEffect instead
  • isLoading for "no data yet": meaning changed in v5 — use isPending
  • enabled with useSuspenseQuery: not available — use conditional rendering
  • keepPreviousData: removed — use placeholderData: keepPreviousData
  • refetch() for changed parameters: include params in queryKey instead, query auto-refetches

v4→v5 Migration Cheatsheet

v4v5Notes
useQuery(['key'], fn, opts)useQuery({ queryKey, queryFn, ...opts })Object syntax only
cacheTimegcTimeRenamed
isLoading (no data)isPendingisLoading = isPending && isFetching
keepPreviousData: trueplaceholderData: keepPreviousDataImport keepPreviousData helper
useErrorBoundarythrowOnErrorRenamed
onSuccess/onError/onSettled on queriesRemovedUse useEffect for side effects
pageParam = 0 defaultinitialPageParam: 0Required for infinite queries
status: 'loading'status: 'pending'Renamed
onError(err, vars, ctx)onError(err, vars, onMutateResult, ctx)v5.89+ added 4th param

Known Issues (v5.90.x)

  • Streaming SSR hydration mismatch — void prefetchQuery + useSuspenseQuery with conditional isFetching render causes hydration errors. Workaround: await prefetch or don't render based on fetchStatus
  • useQuery hydration error with prefetching — useQuery + server prefetch can mismatch isLoading between server/client. Use useSuspenseQuery instead
  • refetchOnMount ignored for errored queries — errors are always stale. Use retryOnMount: false in addition to refetchOnMount: false
  • useMutationState types — mutation.state.variables typed as unknown due to fuzzy matching. Cast explicitly in select callback
  • invalidateQueries only refetches active queries — use refetchType: 'all' to include inactive queries
  • Readonly query keys break in v5.90.8 — fixed in v5.90.9+

Key Patterns

// Dependent queries (B waits for A)
const { data: user } = useQuery({ queryKey: ['user', id], queryFn: () => fetchUser(id) })
const { data: posts } = useQuery({
  queryKey: ['posts', user?.id],
  queryFn: () => fetchPosts(user!.id),
  enabled: !!user,
})

// Parallel queries
const results = useQueries({
  queries: ids.map(id => ({ queryKey: ['item', id], queryFn: () => fetchItem(id) })),
  combine: (results) => ({ data: results.map(r => r.data), pending: results.some(r => r.isPending) }),
})

// Prefetch on hover
const handleHover = () => queryClient.prefetchQuery({ queryKey: ['item', id], queryFn: () => fetchItem(id) })

// Infinite scroll
useInfiniteQuery({
  queryKey: ['posts'],
  queryFn: ({ pageParam }) => fetchPosts(pageParam),
  initialPageParam: 0,
  getNextPageParam: (lastPage) => lastPage.nextCursor,
})

// Query cancellation
queryFn: async ({ signal }) => {
  const res = await fetch(`/api/search?q=${query}`, { signal })
  return res.json()
}

// Data transformation
useQuery({ queryKey: ['todos'], queryFn: fetchTodos, select: (data) => data.filter(t => t.completed) })

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Implement web accessibility (a11y) best practices following WCAG guidelines to create inclusive, accessible user interfaces.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

fellipeutaka/kanpeki332026년 8월 28일 업데이트

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

fellipeutaka/kanpeki332026년 8월 28일 업데이트

bun

무료

Bun runtime, package manager, bundler, and test runner. Use when running scripts with bun, managing packages, serving HTTP with Bun.serve, querying databases with Bun.sql/bun:sqlite/Bun.redis, shell scripting with $, using S3/file I/O, writing tests with bun:test, bundling or compiling to executable, or using any Bun-specific API (spawn, glob, semver, FFI, workers, plugins, HTMLRewriter).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

fellipeutaka/kanpeki332026년 8월 28일 업데이트

Create high-quality git commits: review/stage intended changes, split into logical commits, and write clear commit messages (including Conventional Commits). Use when the user asks to commit, craft a commit message, stage changes, or split work into multiple commits.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

fellipeutaka/kanpeki332026년 8월 28일 업데이트

denji

무료

Manage SVG icons as framework components using Denji CLI. Use when the user needs to add, remove, list, or manage SVG icons in React, Preact, Solid, Qwik, Vue, or Svelte projects. Triggers include requests to "add an icon", "set up icons", "manage SVG icons", "remove an icon", "list icons", or any task involving Iconify icons as framework components.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

fellipeutaka/kanpeki332026년 8월 28일 업데이트

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

fellipeutaka/kanpeki332026년 8월 28일 업데이트

fellipeutaka의 스킬 모두 보기

이 스킬의 문제 신고