Command Palette

Search for a command to run...

UnylyUnyly
Back to skills

tanstack-query

FreeNo executable scriptsNot checked

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

Mindrallyby Mindrally★ 323 GitHub stars

About this skill

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
Full SKILL.md on GitHub

Install tanstack-query in Claude Code & Claude Desktop

Sign up to install this skill

Create a free account to reveal the install command and save the skill to your library.

  • Reveal the one-line install command
  • Save skills to your synced library
  • Get notified when skills update
Sign up freeI already have an account

Allowed tools

Tools this skill is permitted to call.

No restriction — this skill can use any tool.

FAQ

What does the tanstack-query skill do?

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.

How do I install the tanstack-query skill?

Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.

Does the tanstack-query skill run scripts?

No, this skill is instructions only (SKILL.md) with no executable scripts.

Related skills

Compare tanstack-query with