Command Palette

Search for a command to run...

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

tanstack-query

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

Best practices for TanStack Query v5 (React Query) server state management, including query key factories, the queryOptions helper, mutations, optimistic…

Mindrallyот Mindrally★ 323 звезды на GitHub

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

TanStack Query Best Practices

TanStack Query (formerly React Query) handles server-state caching, background updates, and stale-data management out of the box. This skill covers v5 patterns and APIs — v5 introduced several breaking changes from v4 that older examples online still don't reflect.

Core Principles

  • Use TanStack Query for all server state management and data fetching; it is not a general client-state manager — keep client-only state in useState/context/a state library instead
  • Minimize useEffect and useState for server data; favor TanStack Query's built-in state management
  • Every query needs a stable, serializable query key that uniquely describes the data it holds
  • Mutations handle writes; queries handle reads — don't blur this boundary
  • Implement proper error handling with user-friendly messages
  • Use TypeScript for full type safety with query responses

v5 Breaking Changes to Watch For

If you see or write any of these v4 patterns, update them:

  • Object syntax only: useQuery, useInfiniteQuery, etc. no longer accept positional arguments (useQuery(key, fn, options)). Always pass a single options object: useQuery({ queryKey, queryFn, ...options }).
  • isPending replaces isLoading as the name for "no data yet and a fetch is in flight" on useMutation. On useQuery, isPending means no cached data exists at all; isLoading is now derived (isPending && isFetching) and still usable for the classic "first load" spinner case.
  • cacheTime renamed to gcTime (garbage collection time).
  • queryOptions() helper for defining reusable, typed query definitions shared between components, loaders, and prefetch calls.
  • useSuspenseQuery (and useSuspenseInfiniteQuery) for Suspense-based data fetching, replacing the old suspense: true option.
  • placeholderData: keepPreviousData replaces the old keepPreviousData: true boolean for pagination.

Project Structure

src/
  api/
    client.ts             # API client configuration
    endpoints/
      users.ts            # User-related API calls
      posts.ts            # Post-related API calls
  queries/
    postKeys.ts            # Query key factory
    postQueryOptions.ts     # queryOptions() definitions
  hooks/
    queries/
      useUsers.ts         # User query hooks
      usePosts.ts         # Post query hooks
    mutations/
      useCreateUser.ts    # User mutation hooks
  providers/
    QueryProvider.tsx     # Query client provider setup
  types/
    api.ts                # API response types

Setup and Configuration

Query Client Configuration

// providers/QueryProvider.tsx
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 minutes; defaults to 0 (always stale) if unset
      gcTime: 1000 * 60 * 30,   // 30 minutes (formerly cacheTime)
      retry: (failureCount, error: any) => error?.status !== 404 && failureCount < 3,
      refetchOnWindowFocus: true,
      refetchOnReconnect: true,
    },
    mutations: {
      retry: 1,
    },
  },
});

export function QueryProvider({ children }: { children: React.ReactNode }) {
  return (
    <QueryClientProvider client={queryClient}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

Instantiate QueryClient once at the app root — never inside a component, or the cache resets on every render.

Query Best Practices

1. Query Key Organization

Use consistent, hierarchical query keys for efficient cache management:

// Query key factory pattern
export const userKeys = {
  all: ['users'] as const,
  lists: () => [...userKeys.all, 'list'] as const,
  list: (filters: UserFilters) => [...userKeys.lists(), filters] as const,
  details: () => [...userKeys.all, 'detail'] as const,
  detail: (id: string) => [...userKeys.details(), id] as const,
};

2. queryOptions Helper (v5)

Define a query once with queryOptions() and reuse the same definition across components, router loaders, and prefetch calls — this keeps the query key, query function, and options in one place instead of duplicating them:

// queries/postQueryOptions.ts
import { queryOptions } from '@tanstack/react-query';
import { postKeys } from './postKeys';
import { fetchPost } from '@/api/endpoints/posts';

export const postQueryOptions = (id: string) =>
  queryOptions({
    queryKey: postKeys.detail(id),
    queryFn: () => fetchPost(id),
    staleTime: 1000 * 60 * 5,
  });

// In a component
const { data } = useQuery(postQueryOptions(postId));

// In a TanStack Router loader — eliminates loading spinners on navigation
export const Route = createFileRoute('/posts/$postId')({
  loader: ({ params, context: { queryClient } }) =>
    queryClient.ensureQueryData(post
Полный SKILL.md на GitHub

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

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

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

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

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

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

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

FAQ

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

Best practices for TanStack Query v5 (React Query) server state management, including query key factories, the queryOptions helper, mutations, optimistic updates, infinite queries, and Suspense mode. Use when fetching or caching server data in React, writing custom query/mutation hooks, setting up a QueryClient, implementing optimistic updates, or migrating v4 patterns to v5.

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

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

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

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

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

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