Command Palette

Search for a command to run...

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

tanstack-query

БесплатноЗапускает вложенные скриптыНе проверен

TanStack Query v5 (React Query) server state management. Use for data fetching, caching, mutations, or encountering v4 migration, stale data, invalidation…

secondskyот secondsky★ 257 звёзд на GitHub15 установок в других каталогах

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

TanStack Query (React Query) v5

Status: Production Ready ✅ Last Updated: 2026-08-03 Dependencies: React 18.0+ (18.3+ recommended), TypeScript 4.9+ (5.x preferred) Latest Versions: @tanstack/[email protected], @tanstack/[email protected], @tanstack/[email protected]


Quick Start (5 Minutes)

1. Install Dependencies

# choose your package manager
pnpm add @tanstack/react-query@latest @tanstack/react-query-devtools@latest
# or
npm install @tanstack/react-query@latest @tanstack/react-query-devtools@latest
# or
bun add @tanstack/react-query@latest @tanstack/react-query-devtools@latest

Why this matters:

  • TanStack Query v5 requires React 18+ (uses useSyncExternalStore)
  • DevTools are essential for debugging queries and mutations
  • v5 has breaking changes from v4 - use latest for all fixes

2. Set Up QueryClient Provider

// src/main.tsx or src/index.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import App from './App'

// Create a client
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
      gcTime: 1000 * 60 * 60, // 1 hour (formerly cacheTime)
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
})

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  </StrictMode>
)

CRITICAL:

  • Wrap entire app with QueryClientProvider
  • Configure staleTime to avoid excessive refetches (default is 0)
  • Use gcTime (not cacheTime - renamed in v5)
  • DevTools should be inside provider

Know the defaults (v5):

  • staleTime: 0 → data is immediately stale, so refetches on mount/focus unless you raise it
  • gcTime: 5 * 60 * 1000 → inactive data is garbage-collected after 5 minutes
  • retry: 3 in browsers, retry: 0 on the server
  • refetchOnWindowFocus: true and refetchOnReconnect: true
  • networkMode: 'online' (requests pause while offline). Switch to 'always' for SSR/prefetch where you don't want cancellation. citeturn1search0turn1search1

3. Create First Query

// src/hooks/useTodos.ts
import { useQuery } from '@tanstack/react-query'

type Todo = {
  id: number
  title: string
  completed: boolean
}

async function fetchTodos(): Promise<Todo[]> {
  const response = await fetch('/api/todos')
  if (!response.ok) {
    throw new Error('Failed to fetch todos')
  }
  return response.json()
}

export function useTodos() {
  return useQuery({
    queryKey: ['todos'],
    queryFn: fetchTodos,
  })
}

// Usage in component:
function TodoList() {
  const { data, isPending, isError, error } = useTodos()

  if (isPending) return <div>Loading...</div>
  if (isError) return <div>Error: {error.message}</div>

  return (
    <ul>
      {data.map(todo => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  )
}

CRITICAL:

  • v5 requires object syntax: useQuery({ queryKey, queryFn })
  • Use isPending (not isLoading - that now means "pending AND fetching")
  • Always throw errors in queryFn for proper error handling
  • QueryKey should be array for consistent cache keys

4. Create First Mutation

// src/hooks/useAddTodo.ts
import { useMutation, useQueryClient } from '@tanstack/react-query'

type NewTodo = {
  title: string
}

async function addTodo(newTodo: NewTodo) {
  const response = await fetch('/api/todos', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(newTodo),
  })
  if (!response.ok) throw new Error('Failed to add todo')
  return response.json()
}

export function useAddTodo() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: addTodo,
    onSuccess: () => {
      // Invalidate and refetch todos
      queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
  })
}

// Usage in component:
function AddTodoForm() {
  const { mutate, isPending } = useAddTodo()

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    const formData = new FormData(e.currentTarget)
    mutate({ title: formData.get('title') as string })
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="title" required />
      <button type="submit" disabled={isPending}>
        {isPending ? 'Adding...' : 'Add Todo'}
      </button>
    </form>
  )
}

Why this works:

  • Mutations use callbacks (onSuccess, onError, onSettled) - queries don't
  • invalidateQueries triggers background refetch
  • Mutations don't cache by default (correct behavior)

The 7-Step Setup Process

Step 1: Install Dependencies

# Core library (required)
pnpm add @tanstack/re
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

Вложенные файлы

assets/example-template.txtexamples/README.mdexamples/basic-graphql-request.tsxexamples/basic.tsxexamples/default-query-function.tsxexamples/infinite-scroll.tsxexamples/nextjs-app-router.tsxexamples/optimistic-update.tsxexamples/pagination.tsxexamples/prefetching.tsxexamples/react-native.tsxexamples/suspense.tsxreferences/advanced-setup.mdreferences/best-practices.mdreferences/common-patterns.mdreferences/configuration-files.mdreferences/example-reference.mdreferences/official-guides-map.mdreferences/testing.mdreferences/top-errors.mdreferences/typescript-patterns.mdreferences/v4-to-v5-migration.mdscripts/example-script.shtemplates/custom-hooks-pattern.tsxtemplates/devtools-setup.tsxtemplates/error-boundary.tsxtemplates/package.jsontemplates/provider-setup.tsxtemplates/query-client-config.tstemplates/use-infinite-query.tsxtemplates/use-mutation-basic.tsxtemplates/use-mutation-optimistic.tsxtemplates/use-query-basic.tsx

FAQ

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

TanStack Query v5 (React Query) server state management. Use for data fetching, caching, mutations, or encountering v4 migration, stale data, invalidation errors.

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

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

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

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

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

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