Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

tanstack-query

БесплатноБез исполняемых скриптовНе проверен

Use when managing server state with TanStack Query v5. Covers query key factories, data transformation, mutations, optimistic updates, authentication, testing…

MadAppGangот MadAppGang★ 290 звёзд на GitHub35 установок в других каталогах

Об этом скилле

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:

  1. 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)
    
  2. Renamed Options:

    • cacheTime → gcTime (garbage collection time)
    • keepPreviousData → placeholderData: keepPreviousData
    • isLoading now means isPending && isFetching
  3. Callbacks Removed from useQuery:

    • onSuccess, onError, onSettled removed from useQuery
    • Use global QueryCache callbacks instead
    • Prevents duplicate executions
  4. Infinite Queries Require initialPageParam:

    • No default value provided
    • Must explicitly set initialPageParam (e.g., 0 or null)
  5. First-Class Suspense:

    • New dedicated hooks: useSuspenseQuery, useSuspenseInfiniteQuery
    • No experimental flag needed
    • Data is never undefined at type level

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>

Architecture: Feature-Based Colocation

Recommended pattern: Group queries with related features, not by file type.

src/features/
├── Todos/
│   ├── index.tsx           # Feature entry point
│   ├── queries.ts          # All React Query logic (keys, functions, hooks)
│   ├── types.ts            # TypeScript types
│   └── components/         # Feature-specific components

Export only custom hooks from query files. Keep query functions and keys private:

// features/todos/queries.ts

// 1. Query Key Factory (hierarchical structure)
const todoKeys = {
  all: ['todos'] as const,
  lists: () => [...todoKeys.all, 'list'] as const,
  list: (filters: string) => [...todoKeys.lists(), { filters }] as const,
  details: () => [...todoKeys.all, 'detail'] as const,
  detail: (id: number) => [...todoKeys.details(), id] as const,
}

// 2. Query Function (private)
const fetchTodos = async (filters: string): Promise<Todo[]> => {
  const response = await axios.get('/api/todos', { params: { filters } })
  return response.data
}

// 3. Custom Hook (public API)
export const useTodosQuery = (filters: string) => {
  return useQuery({
    queryKey: todoKeys.list(filters),
    queryFn: () => fetchTodos(filters),
    staleTime: 30_000, // Fresh for 30 seconds
  })
}

Benefits:

  • Prevents key/function mismatches
  • Clean public API
  • Encapsulation and maintainability
  • Easy to locate all query logic for a feature

Query Key Factories (Essential)

Structure keys hierarchically from generic to specific:

// ✅ Correct hierarchy
[
Полный SKILL.md на GitHub

Установить tanstack-query в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл tanstack-query?

Use when managing server state with TanStack Query v5. Covers query key factories, data transformation, mutations, optimistic updates, authentication, testing with MSW, and best practices for async state management.

Как установить скилл tanstack-query?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл tanstack-query запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить tanstack-query с