tanstack-query
БесплатноБез исполняемых скриптовНе проверенComprehensive TanStack Query v5 patterns for async state management. Covers breaking changes, query key factories, data transformation, mutations, optimistic…
от MadAppGang★ 290 звёзд на GitHubОб этом скилле
TanStack Query v5 - Complete Guide
TanStack Query v5 (October 2023) is the async state manager for this project. It requires React 18+, features first-class Suspense support, improved TypeScript inference, and a 20% smaller bundle. This section covers production-ready patterns based on official documentation and community best practices.
Breaking Changes in v5
Key updates you need to know:
Single Object Signature: All hooks now accept one configuration object:
// ✅ v5 - single object useQuery({ queryKey, queryFn, ...options }) // ❌ v4 - multiple overloads (deprecated) useQuery(queryKey, queryFn, options)Renamed Options:
cacheTime→gcTime(garbage collection time)keepPreviousData→placeholderData: keepPreviousDataisLoadingnow meansisPending && isFetching
Callbacks Removed from useQuery:
onSuccess,onError,onSettledremoved fromuseQuery- Use global QueryCache callbacks instead
- Prevents duplicate executions
Infinite Queries Require initialPageParam:
- No default value provided
- Must explicitly set
initialPageParam(e.g.,0ornull)
First-Class Suspense:
- New dedicated hooks:
useSuspenseQuery,useSuspenseInfiniteQuery - No experimental flag needed
- Data is never undefined at type level
- New dedicated hooks:
Migration: Use the official codemod for automatic migration: npx @tanstack/query-codemods v5/replace-import-specifier
Smart Defaults
Query v5 ships with production-ready defaults:
{
staleTime: 0, // Data instantly stale (refetch on mount)
gcTime: 5 * 60_000, // Keep unused cache for 5 minutes
retry: 3, // 3 retries with exponential backoff
refetchOnWindowFocus: true,// Refetch when user returns to tab
refetchOnReconnect: true, // Refetch when network reconnects
}
Philosophy: React Query is an async state manager, not a data fetcher. You provide the Promise; Query manages caching, background updates, and synchronization.
Client Setup
// src/app/providers.tsx
import { QueryClient, QueryClientProvider, QueryCache } from '@tanstack/react-query'
import { toast } from './toast' // Your notification system
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 0, // Adjust per-query
gcTime: 5 * 60_000, // 5 minutes (v5: formerly cacheTime)
retry: (failureCount, error) => {
// Don't retry on 401 (authentication errors)
if (error?.response?.status === 401) return false
return failureCount < 3
},
},
},
queryCache: new QueryCache({
onError: (error, query) => {
// Only show toast for background errors (when data exists)
if (query.state.data !== undefined) {
toast.error(`Something went wrong: ${error.message}`)
}
},
}),
})
export function AppProviders({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
)
}
DevTools Setup (auto-excluded in production):
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
Server-Side Rendering Configuration
When using TanStack Query with SSR (Next.js, Remix, TanStack Start), configure server-specific defaults:
// Server-side QueryClient configuration
export function makeQueryClient() {
return new QueryClient({
defaultOptions: {
queries: {
// Server: Don't retry on server (fail fast)
retry: typeof window === 'undefined' ? 0 : 3,
// Server: Data is always fresh when rendered
staleTime: 60_000, // 1 minute
},
},
})
}
Server vs Client Defaults:
| Option | Client Default | Server Recommended | Why |
|---|---|---|---|
retry |
3 | 0 | Server should fail fast, not retry loops |
staleTime |
0 | 60_000+ | Server-rendered data is fresh |
gcTime |
5 min | Infinity | No garbage collection needed on server |
refetchOnWindowFocus |
true | false | No window on server |
refetchOnReconnect |
true | false | No reconnect on server |
Important: In SPA-only apps (TanStack Router + Vite), you don't need these server defaults. They're only relevant for SSR frameworks.
Streaming SSR (Experimental)
For Next.js App Router, @tanstack/react-query-next-experimental enables streaming:
pnpm add @tanstack/react-query-next-experimental
Setup:
// app/providers.tsx
'use client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryStreamedHydration } from '@tanstack/react-query-next-experimental'
function makeQueryClient() {
return new Query
Установить tanstack-query в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл tanstack-query?
Comprehensive TanStack Query v5 patterns for async state management. Covers breaking changes, query key factories, data transformation, mutations, optimistic updates, authentication, testing with MSW, and anti-patterns. Use for all server state management, data fetching, and cache invalidation tasks.
Как установить скилл tanstack-query?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл tanstack-query запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic