Tanstack Query logo

Tanstack Query

Organization
blencorp
tanstack-query

TanStack Query v5 data fetching patterns including useSuspenseQuery, useQuery, mutations, cache management, and API service integration. Use when fetching data, managing server state, or working with TanStack Query hooks.

Overview

Publisherblencorp
Repositoryclaude-code-kit
Skill nametanstack-query
Stars
102
Forks
14
Bundled files
4
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 4 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by blencorp on GitHub. Read the source before you install it.

Installation

Install the Tanstack Query AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/blencorp/claude-code-kit.git /tmp/claude-code-kit
mkdir -p .claude/skills
cp -r /tmp/claude-code-kit/cli/kits/tanstack-query/skills/tanstack-query .claude/skills/tanstack-query
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Tanstack Query in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Tanstack Query on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Tanstack Query is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

TanStack Query Patterns

Purpose

Modern data fetching with TanStack Query v5 (latest: 5.90.5, November 2025), emphasizing Suspense-based queries, cache-first strategies, and centralized API services.

Note: v5 (released October 2023) has breaking changes from v4:

  • isLoadingisPending for status
  • cacheTimegcTime (garbage collection time)
  • React 18.0+ required
  • Callbacks removed from useQuery (onError, onSuccess, onSettled)
  • keepPreviousData replaced with placeholderData function

When to Use This Skill

  • Fetching data with TanStack Query
  • Using useSuspenseQuery or useQuery
  • Managing mutations
  • Cache invalidation and updates
  • API service patterns

Quick Start

Primary Pattern: useSuspenseQuery

For all new components, use useSuspenseQuery:

typescript
import { useSuspenseQuery } from '@tanstack/react-query';
import { postsApi } from '~/features/posts/api/postsApi';

function PostList() {
  const { data: posts } = useSuspenseQuery({
    queryKey: ['posts'],
    queryFn: postsApi.getAll,
  });

  return (
    <div>
      {posts.map(post => (
        <PostCard key={post.id} post={post} />
      ))}
    </div>
  );
}

// Wrap with Suspense
<Suspense fallback={<PostsSkeleton />}>
  <PostList />
</Suspense>

Benefits:

  • No isLoading checks needed
  • Integrates with Suspense boundaries
  • Cleaner component code
  • Consistent loading UX

useSuspenseQuery Patterns

Basic Usage

typescript
const { data } = useSuspenseQuery({
  queryKey: ['user', userId],
  queryFn: () => userApi.get(userId),
});

// data is never undefined - guaranteed by Suspense
return <div>{data.name}</div>;

With Parameters

typescript
function UserPosts({ userId }: { userId: string }) {
  const { data: posts } = useSuspenseQuery({
    queryKey: ['users', userId, 'posts'],
    queryFn: () => postsApi.getByUser(userId),
  });

  return <div>{posts.length} posts</div>;
}

Dependent Queries

typescript
function PostDetails({ postId }: { postId: string }) {
  // First query
  const { data: post } = useSuspenseQuery({
    queryKey: ['posts', postId],
    queryFn: () => postsApi.get(postId),
  });

  // Second query depends on first
  const { data: author } = useSuspenseQuery({
    queryKey: ['users', post.authorId],
    queryFn: () => userApi.get(post.authorId),
  });

  return <div>{author.name} wrote {post.title}</div>;
}

useQuery (Legacy Pattern)

Use useQuery only when you need loading/error states in the component:

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

function Component() {
  const { data, isPending, error } = useQuery({
    queryKey: ['posts'],
    queryFn: postsApi.getAll,
  });

  if (isPending) return <Spinner />;
  if (error) return <Error error={error} />;

  return <div>{data.map(...)}</div>;
}

When to use useQuery vs useSuspenseQuery:

  • Use useSuspenseQuery by default (preferred)
  • Use useQuery only when you need component-level loading states
  • Most cases should use useSuspenseQuery + Suspense boundaries

Mutations

Basic Mutation

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

function CreatePostButton() {
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: postsApi.create,
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries({ queryKey: ['posts'] });
    },
  });

  const handleCreate = () => {
    mutation.mutate({
      title: 'New Post',
      content: 'Content here',
    });
  };

  return (
    <button onClick={handleCreate} disabled={mutation.isPending}>
      {mutation.isPending ? 'Creating...' : 'Create Post'}
    </button>
  );
}

Optimistic Updates

typescript
const mutation = useMutation({
  mutationFn: postsApi.update,
  onMutate: async (updatedPost) => {
    // Cancel outgoing refetches
    await queryClient.cancelQueries({ queryKey: ['posts', updatedPost.id] });

    // Snapshot previous value
    const previousPost = queryClient.getQueryData(['posts', updatedPost.id]);

    // Optimistically update
    queryClient.setQueryData(['posts', updatedPost.id], updatedPost);

    // Return context with snapshot
    return { previousPost };
  },
  onError: (err, updatedPost, context) => {
    // Rollback on error
    queryClient.setQueryData(
      ['posts', updatedPost.id],
      context.previousPost
    );
  },
  onSettled: (data, error, variables) => {
    // Refetch after mutation
    queryClient.invalidateQueries({ queryKey: ['posts', variables.id] });
  },
});

Cache Management

Invalidation

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

const queryClient = useQueryClient();

// Invalidate all posts queries
queryClient.invalidateQueries({ queryKey: ['posts'] });

// Invalidate specific post
queryClient.invalidateQueries({ queryKey: ['posts', postId] });

// Invalidate all queries
queryClient.invalidateQueries();

Manual Updates

typescript
// Update cache directly
queryClient.setQueryData(['posts', postId], newPost);

// Update with function
queryClient.setQueryData(['posts'], (oldPosts) => [
  ...oldPosts,
  newPost,
]);

Prefetching

typescript
// Prefetch data
await queryClient.prefetchQuery({
  queryKey: ['posts', postId],
  queryFn: () => postsApi.get(postId),
});

// In a component
const prefetchPost = (postId: string) => {
  queryClient.prefetchQuery({
    queryKey: ['posts', postId],
    queryFn: () => postsApi.get(postId),
  });
};

<Link
  to={`/posts/${post.id}`}
  onMouseEnter={() => prefetchPost(post.id)}
>
  {post.title}
</Link>

API Service Pattern

Centralized API Service

typescript
// features/posts/api/postsApi.ts
import { apiClient } from '@/lib/apiClient';
import type { Post, CreatePostDto, UpdatePostDto } from '~/types/post';

export const postsApi = {
  getAll: async (): Promise<Post[]> => {
    const response = await apiClient.get('/posts');
    return response.data;
  },

  get: async (id: string): Promise<Post> => {
    const response = await apiClient.get(`/posts/${id}`);
    return response.data;
  },

  create: async (data: CreatePostDto): Promise<Post> => {
    const response = await apiClient.post('/posts', data);
    return response.data;
  },

  update: async (id: string, data: UpdatePostDto): Promise<Post> => {
    const response = await apiClient.put(`/posts/${id}`, data);
    return response.data;
  },

  delete: async (id: string): Promise<void> => {
    await apiClient.delete(`/posts/${id}`);
  },

  getByUser: async (userId: string): Promise<Post[]> => {
    const response = await apiClient.get(`/users/${userId}/posts`);
    return response.data;
  },
};

Usage in Components

typescript
import { postsApi } from '~/features/posts/api/postsApi';

// In query
const { data } = useSuspenseQuery({
  queryKey: ['posts'],
  queryFn: postsApi.getAll,
});

// In mutation
const mutation = useMutation({
  mutationFn: postsApi.create,
});

Query Keys

Key Structure

typescript
// List queries
['posts']                          // All posts
['posts', { status: 'published' }] // Filtered posts

// Detail queries
['posts', postId]                  // Single post
['posts', postId, 'comments']      // Post comments

// Nested resources
['users', userId, 'posts']         // User's posts
['users', userId, 'posts', postId] // Specific user post

Key Factories

typescript
// features/posts/api/postKeys.ts
export const postKeys = {
  all: ['posts'] as const,
  lists: () => [...postKeys.all, 'list'] as const,
  list: (filters: string) => [...postKeys.lists(), { filters }] as const,
  details: () => [...postKeys.all, 'detail'] as const,
  detail: (id: string) => [...postKeys.details(), id] as const,
  comments: (id: string) => [...postKeys.detail(id), 'comments'] as const,
};

// Usage
const { data } = useSuspenseQuery({
  queryKey: postKeys.detail(postId),
  queryFn: () => postsApi.get(postId),
});

// Invalidate all post lists
queryClient.invalidateQueries({ queryKey: postKeys.lists() });

Error Handling

With Error Boundaries

typescript
import { ErrorBoundary } from 'react-error-boundary';

<ErrorBoundary fallback={<ErrorFallback />}>
  <Suspense fallback={<Loading />}>
    <DataComponent />
  </Suspense>
</ErrorBoundary>

// In component
function DataComponent() {
  const { data } = useSuspenseQuery({
    queryKey: ['data'],
    queryFn: fetchData,
    // Errors automatically caught by ErrorBoundary
  });

  return <div>{data}</div>;
}

Retry and Cache Configuration

typescript
const { data } = useQuery({
  queryKey: ['posts'],
  queryFn: postsApi.getAll,
  retry: 3,              // Retry 3 times
  retryDelay: 1000,      // Wait 1s between retries
  gcTime: 5 * 60 * 1000, // Garbage collection time: 5 minutes (v5: was 'cacheTime')
});

Best Practices

1. Use Suspense by Default

typescript
// ✅ Good: useSuspenseQuery + Suspense
<Suspense fallback={<Skeleton />}>
  <DataComponent />
</Suspense>

function DataComponent() {
  const { data } = useSuspenseQuery({...});
  return <div>{data}</div>;
}

// ❌ Avoid: useQuery with manual loading
function DataComponent() {
  const { data, isPending } = useQuery({...});
  if (isPending) return <Spinner />;
  return <div>{data}</div>;
}

2. Consistent Query Keys

typescript
// ✅ Good: Use key factories
const { data } = useSuspenseQuery({
  queryKey: postKeys.detail(id),
  queryFn: () => postsApi.get(id),
});

// ❌ Avoid: Inconsistent keys
const { data } = useSuspenseQuery({
  queryKey: ['post', id], // Different format
  queryFn: () => postsApi.get(id),
});

3. Centralized API Services

typescript
// ✅ Good: API service
const { data } = useSuspenseQuery({
  queryKey: ['posts'],
  queryFn: postsApi.getAll,
});

// ❌ Avoid: Inline fetching
const { data } = useSuspenseQuery({
  queryKey: ['posts'],
  queryFn: async () => {
    const res = await fetch('/api/posts');
    return res.json();
  },
});

Additional Resources

For more patterns, see:

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Tanstack Query AI skill do?

TanStack Query v5 data fetching patterns including useSuspenseQuery, useQuery, mutations, cache management, and API service integration. Use when fetching data, managing server state, or working with TanStack Query hooks.

Why use Tanstack Query on TypingMind?

Because you install it once and use it with any model. Tanstack Query is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Tanstack Query in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/blencorp/claude-code-kit/tree/main/cli/kits/tanstack-query/skills/tanstack-query. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Tanstack Query?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Tanstack Query?

As many as you like. As long as a model supports skills, you can use Tanstack Query with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Tanstack Query AI skill free?

Yes. It is published on GitHub by blencorp under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇