Agent skill

Tanstack Query Expert

by davila7 in davila7/claude-code-templates

Expert in TanStack Query (React Query) — asynchronous state management.

MITAuto-check passedDevelopment

Install Tanstack Query Expert

skills CLI
$ npx skills add davila7/claude-code-templates --skill tanstack-query-expert -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install davila7/claude-code-templates tanstack-query-expert --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/davila7/claude-code-templates.git skills-src && mkdir -p .claude/skills && cp -r skills-src/cli-tool/components/skills/web-development/tanstack-query-expert .claude/skills/tanstack-query-expert && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
tanstack-query-expert
GitHub stars
32k
Used in
3 other repos
Token cost
~2.3k tokens
SKILL.md length
525 words
Files
1
Skills in repo
477
Repo updated
First seen
Licence
MIT

At a glance

Expert in TanStack Query (React Query) — asynchronous state management.

  • Tasks that involve Async programming
  • SKILL.md covers When to Use This Skill, Core Concepts, Query Definition Patterns and Mutations & Cache Invalidation, plus 3 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Tasks that involve State management

What it does

Tanstack Query Expert is an agent skill from davila7/claude-code-templates. Expert in TanStack Query (React Query) — asynchronous state management. Covers data fetching, stale time configuration, mutations, optimistic updates, and Next.js App Router (SSR) integration.

Its SKILL.md is about 2.3k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Development, covering Async programming and State management. It works with TanStack and Next.js. The repository describes itself as: CLI tool for configuring and monitoring Claude Code. The licence is MIT.

When your agent uses it

  • Tasks that involve Async programming
  • Tasks that involve State management

Example prompts

  • “/tanstack-query-expert”

What it can do on your machine

Read from SKILL.md and the folder at commit 4c82aba. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Tanstack Query Expert loads about 2.3k tokens when it runs. Until then it costs about 54 tokens; SKILL.md has 525 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~54
When it runs · the whole SKILL.md, loaded when a task matches
~2.3k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from davila7/claude-code-templates at commit 4c82aba, republished under its MIT licence (© davila7). 525 words, ~2,260 tokens.

Download SKILL.mdSave it as .claude/skills/tanstack-query-expert/SKILL.md (or your agent's skills folder).
name
tanstack-query-expert
description
Expert in TanStack Query (React Query) — asynchronous state management. Covers data fetching, stale time configuration, mutations, optimistic updates, and Next.js App Router (SSR) integration.
risk
safe
source
community
date_added
2026-03-07

TanStack Query Expert

You are a production-grade TanStack Query (formerly React Query) expert. You help developers build robust, performant asynchronous state management layers in React and Next.js applications. You master declarative data fetching, cache invalidation, optimistic UI updates, background syncing, error boundaries, and server-side rendering (SSR) hydration patterns.

When to Use This Skill

  • Use when setting up or refactoring data fetching logic (replacing useEffect + useState)
  • Use when designing query keys (Array-based, strictly typed keys)
  • Use when configuring global or query-specific staleTime, gcTime, and retry behavior
  • Use when writing useMutation hooks for POST/PUT/DELETE requests
  • Use when invalidating the cache (queryClient.invalidateQueries) after a mutation
  • Use when implementing Optimistic Updates for instant UX feedback
  • Use when integrating TanStack Query with Next.js App Router (Server Components + Client Boundary hydration)

Core Concepts

Why TanStack Query?

TanStack Query is not just for fetching data; it's an asynchronous state manager. It handles caching, background updates, deduplication of multiple requests for the same data, pagination, and out-of-the-box loading/error states.

Rule of Thumb: Never use useEffect to fetch data if TanStack Query is available in the stack.

Query Definition Patterns

The Custom Hook Pattern (Best Practice)

Always abstract useQuery calls into custom hooks to encapsulate the fetching logic, TypeScript types, and query keys.

typescript
import { useQuery } from '@tanstack/react-query';

// 1. Define strict types
type User = { id: string; name: string; status: 'active' | 'inactive' };

// 2. Define the fetcher function
const fetchUser = async (userId: string): Promise<User> => {
  const res = await fetch(`/api/users/${userId}`);
  if (!res.ok) throw new Error('Failed to fetch user');
  return res.json();
};

// 3. Export a custom hook
export const useUser = (userId: string) => {
  return useQuery({
    queryKey: ['users', userId], // Array-based query key
    queryFn: () => fetchUser(userId),
    staleTime: 1000 * 60 * 5, // Data is fresh for 5 minutes (no background refetching)
    enabled: !!userId, // Dependent query: only run if userId exists
  });
};
Advanced Query Keys

Query keys uniquely identify the cache. They must be arrays, and order matters.

typescript
// Filtering / Sorting
useQuery({
  queryKey: ['issues', { status: 'open', sort: 'desc' }],
  queryFn: () => fetchIssues({ status: 'open', sort: 'desc' })
});

// Factory pattern for query keys (Highly recommended for large apps)
export const issueKeys = {
  all: ['issues'] as const,
  lists: () => [...issueKeys.all, 'list'] as const,
  list: (filters: string) => [...issueKeys.lists(), { filters }] as const,
  details: () => [...issueKeys.all, 'detail'] as const,
  detail: (id: number) => [...issueKeys.details(), id] as const,
};

Mutations & Cache Invalidation

Basic Mutation with Invalidation

When you modify data on the server, you must tell the client cache that the old data is now stale.

typescript
import { useMutation, useQueryClient } from '@tanstack/react-query';

export const useCreatePost = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (newPost: { title: string }) => {
      const res = await fetch('/api/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newPost),
      });
      return res.json();
    },
    // On success, invalidate the 'posts' cache to trigger a background refetch
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['posts'] });
    },
  });
};
Optimistic Updates

Give the user instant feedback by updating the cache before the server responds, and rolling back if the request fails.

typescript
export const useUpdateTodo = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: updateTodoFn,
    
    // 1. Triggered immediately when mutate() is called
    onMutate: async (newTodo) => {
      // Cancel any outgoing refetches so they don't overwrite our optimistic update
      await queryClient.cancelQueries({ queryKey: ['todos'] });

      // Snapshot the previous value
      const previousTodos = queryClient.getQueryData(['todos']);

      // Optimistically update to the new value
      queryClient.setQueryData(['todos'], (old: any) => 
        old.map((todo: any) => todo.id === newTodo.id ? { ...todo, ...newTodo } : todo)
      );

      // Return a context object with the snapshotted value
      return { previousTodos };
    },
    
    // 2. If the mutation fails, use the context returned from onMutate to roll back
    onError: (err, newTodo, context) => {
      queryClient.setQueryData(['todos'], context?.previousTodos);
    },
    
    // 3. Always refetch after error or success to ensure server sync
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });
};

Next.js App Router Integration

Initializing the Provider
typescript
// app/providers.tsx
'use client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useState } from 'react'

export default function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 60 * 1000, // 1 minute
            refetchOnWindowFocus: false, // Prevents aggressive refetching on tab switch
          },
        },
      })
  )

  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  )
}
Server Component Pre-fetching (Hydration)

Pre-fetch data on the server and pass it to the client without prop-drilling or initialData.

typescript
// app/posts/page.tsx (Server Component)
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';
import PostsList from './PostsList'; // Client Component

export default async function PostsPage() {
  const queryClient = new QueryClient();

  // Prefetch the data on the server
  await queryClient.prefetchQuery({
    queryKey: ['posts'],
    queryFn: fetchPostsServerSide,
  });

  // Dehydrate the cache and pass it to the HydrationBoundary
  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <PostsList />
    </HydrationBoundary>
  );
}
typescript
// app/posts/PostsList.tsx (Client Component)
'use client'
import { useQuery } from '@tanstack/react-query';

export default function PostsList() {
  // This will NOT trigger a network request on mount! 
  // It reads instantly from the dehydrated server cache.
  const { data } = useQuery({
    queryKey: ['posts'],
    queryFn: fetchPostsClientSide,
  });

  return <div>{data.map(post => <p key={post.id}>{post.title}</p>)}</div>;
}
Show full SKILL.md (230 more words)Show less

Best Practices

  • ✅ Do: Create Query Key factories so you don't misspell ['users'] vs ['user'] across different files.
  • ✅ Do: Set a global staleTime (e.g., 1000 * 60) if your data doesn't change every second. The default staleTime is 0, meaning TanStack Query will trigger a background refetch on every component remount by default.
  • ✅ Do: Use queryClient.setQueryData sparingly. It's usually better to just invalidateQueries and let TanStack Query refetch the fresh data organically.
  • ✅ Do: Abstract all useMutation and useQuery calls into custom hooks. Views should only say const { mutate } = useCreatePost().
  • ❌ Don't: Pass primitive callbacks inline directly to useQuery without memoization if you rely on closures. (Instead, rely on the queryKey dependency array).
  • ❌ Don't: Sync query data into local React state (e.g., useEffect(() => setLocalState(data), [data])). Use the query data directly. If you need derived state, derive it during render.

Troubleshooting

Problem: Infinite fetching loop in the network tab. Solution: Check your queryFn. If your fetch logic isn't structured correctly, or throws an unhandled exception before hitting the return, TanStack Query will retry automatically up to 3 times (default). If wrapped in an unstable useEffect, it loops infinitely. Check retry: false for debugging.

Problem: staleTime vs gcTime (formerly cacheTime) confusion. Solution: staleTime governs when a background refetch is triggered. gcTime governs how long the inactive data stays in memory after the component unmounts. If gcTime < staleTime, data will be deleted before it even gets stale!

© davila7, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in cli-tool/components/skills/web-development/tanstack-query-expert of davila7/claude-code-templates.

Open the folder on GitHubat commit 4c82aba

Used in 3 other repositories

We found 12 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 3 other GitHub owners. This page covers the copy in davila7/claude-code-templates, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Tanstack Query Expert next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Tanstack Query Expert compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Tanstack Query Expert this skilldavila7/claude-code-templates32k3 repos~2.3kAutomated safety check: PassMIT
Tanstack Querybskimball/tanstack-hono1191 repos~5.4kAutomated safety check: PassMIT
Moai Ref React Patternsmodu-ai/moai-adk1.2k—~1.8kAutomated safety check: PassApache-2.0
Component Patternsrevfactory/harness-1001.3k—~1.5kAutomated safety check: PassApache-2.0
Olore Tanstack Form Latestolorehq/olore103—~1.1kAutomated safety check: PassMIT
Feature Sliced Designfeature-sliced/skills109—~5.5kAutomated safety check: PassNone

Similar skills

  • Tanstack Query

    bskimball/tanstack-hono

    Powerful asynchronous state management, server-state utilities, and data fetching for TS/JS, React, Vue, Solid, Svelte & Angular.

    119 GitHub starsUsed in 1 repo~5.4k tokens
    Frontend & DesignAuto-check passed
  • Moai Ref React Patterns

    modu-ai/moai-adk

    React/Next.js component design patterns, state management strategies, and project structure reference for frontend development.

    1.2k GitHub stars~1.8k tokensUpdated today
    Frontend & DesignAuto-check passed
  • Component Patterns

    revfactory/harness-100

    React/Next.js component design pattern library. An agent skill from revfactory/harness-100.

    1.3k GitHub stars~1.5k tokensUpdated 6 mo ago
    Frontend & DesignAuto-check passed
  • Local TanStack Form documentation reference (latest, v1.33.5).

    103 GitHub stars~1.1k tokensUpdated yesterday
    MobileAuto-check passed
  • Feature Sliced Design

    feature-sliced/skills

    Official Feature-Sliced Design (FSD) v2.1 skill for applying the methodology to frontend projects.

    109 GitHub stars~5.5k tokensUpdated 21 days ago
    Frontend & DesignAuto-check passed
  • Nextjs15 Init

    bear2u/my-skills

    A skill your agent uses when user wants to create a new Next.js 15 project (Todo/Blog/Dashboard/E-commerce/Custom domain) with App Router, ShadCN, Zustand, Tanstack Query, and modern Next.js stack

    933 GitHub stars~2.4k tokensUpdated 3 mo ago
    Frontend & DesignAuto-check passed

More from davila7/claude-code-templates

All 477 skills in this repo
  • Perplexity Web Search

    davila7/claude-code-templates

    Runs web-grounded searches through Perplexity's Sonar models over OpenRouter for current events, recent literature and cited facts beyond the model's training cutoff.

    32k GitHub starsUsed in 12 repos~3.5k tokens
    Auto-check: notes
  • Neuropixels Data Analysis

    davila7/claude-code-templates

    Analyzes Neuropixels recordings from SpikeGLX or Open Ephys through preprocessing, drift correction, Kilosort4 spike sorting, quality metrics and curation.

    32k GitHub starsUsed in 10 repos~2.8k tokens
    Auto-check passed
  • Scientific Venue Templates

    davila7/claude-code-templates

    Supplies LaTeX templates and formatting rules for journals, conferences, posters, and grant proposals, then can check a draft against them.

    32k GitHub starsUsed in 9 repos~5.1k tokens
    Auto-check: notes
  • Brand Voice Content Creator

    davila7/claude-code-templates

    Analyzes a brand's existing writing to lock in a consistent voice, then builds SEO blog posts and platform-specific social content around it.

    32k GitHub starsUsed in 2 repos~1.9k tokens
    Auto-check passed
  • CAPA Officer

    davila7/claude-code-templates

    Guides corrective and preventive action (CAPA) work in a quality management system, from initiation and root cause analysis through effectiveness verification.

    32k GitHub starsUsed in 1 repo~2k tokens
    Auto-check passed
  • Fda Consultant Specialist

    davila7/claude-code-templates

    Senior FDA consultant and specialist for medical device companies including HIPAA compliance and requirement management.

    32k GitHub starsUsed in 1 repo~2.7k tokens
    Auto-check passed

Works with

Questions about Tanstack Query Expert

What does Tanstack Query Expert do?

Expert in TanStack Query (React Query) — asynchronous state management. Tanstack Query Expert is an agent skill from davila7/claude-code-templates. Expert in TanStack Query (React Query) — asynchronous state management.

When should I use Tanstack Query Expert?

Tanstack Query Expert fits situations like: tasks that involve Async programming; tasks that involve State management.

How do I install Tanstack Query Expert in Claude Code?

Run `npx skills add davila7/claude-code-templates --skill tanstack-query-expert -a claude-code`. Or copy the skill folder (cli-tool/components/skills/web-development/tanstack-query-expert in davila7/claude-code-templates) into .claude/skills/tanstack-query-expert in your project. Claude Code loads it when a task matches its description.

How do I install Tanstack Query Expert in Codex?

Run `npx skills add davila7/claude-code-templates --skill tanstack-query-expert -a codex`. Or copy the skill folder (cli-tool/components/skills/web-development/tanstack-query-expert in davila7/claude-code-templates) into .agents/skills/tanstack-query-expert in your project. Codex loads it when a task matches its description.

Can I use Tanstack Query Expert in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add davila7/claude-code-templates --skill tanstack-query-expert -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/tanstack-query-expert, .gemini/skills/tanstack-query-expert, .github/skills/tanstack-query-expert and .opencode/skills/tanstack-query-expert in your project.

What does Tanstack Query Expert need to run?

SKILL.md names no scripts, command-line tools or credentials: Tanstack Query Expert is instructions for the agent only.

Does Tanstack Query Expert access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Tanstack Query Expert safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Tanstack Query Expert use?

Tanstack Query Expert is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Tanstack Query Expert use?

About 2.3k tokens (SKILL.md is roughly 9k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Tanstack Query Expert?

Skills that share tags, products or a category with Tanstack Query Expert: Tanstack Query (bskimball/tanstack-hono, 119 stars), Moai Ref React Patterns (modu-ai/moai-adk, 1.2k stars), Component Patterns (revfactory/harness-100, 1.3k stars) and Olore Tanstack Form Latest (olorehq/olore, 103 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Tanstack Query Expert?

davila7 (a GitHub user) maintains it in davila7/claude-code-templates, which has 32,432 GitHub stars. The repository holds 477 skills in this directory. The repository was last updated on October 7, 2026.

Source: davila7/claude-code-templates on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.