Token导航 LogoToken导航

Agent Skill · 前端设计

tanstack-query(tanstack 查询)

tanstack-query 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

tanstack-query 是前端设计类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为调用外部服务;许可证信息还不明确,第三方扫描已通过,按安装量在前端设计类的 10,216 个 Skill 里排第 5,591。

总安装 642周安装 27GitHub Stars 12下载 225核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:tanstack-query(tanstack 查询)
来源仓库:https://github.com/claude-dev-suite/claude-dev-suite
仓库路径:skills/tanstack-query
安装命令:
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill tanstack-query
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill tanstack-query

这个 Skill 是做什么的

前端设计类 Skill 关注页面结构、视觉规范和组件写法,输出通常是可运行的界面代码。

用于处理前端数据获取与状态管理,提升应用响应性。适合实现缓存策略、自动重试和后台数据同步。使用时需配置 QueryClient 并定义合理的 staleTime 和重试次数。涉及敏感数据时应注意缓存清理与权限校验机制。tanstack-query 属于前端设计类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/tanstack-query

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill tans…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要调用外部服务,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

tanstack-query 怎么安装?

在终端执行 npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill tanstack-query。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

tanstack-query 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

tanstack-query 需要什么权限?

权限级别是调用外部服务。该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

tanstack-query 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

tanstack-query 用的人多吗?

公开数据是累计安装 642 次,近一周安装 27 次,下载 225 次,GitHub 12 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

tanstack-query 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理前端设计类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

前端设计类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
frontend-design

前端设计 · Codex、Claude

8,823,360126,072只读MIT通过
vercel-composition-patterns

Vercel 组合模式 · Codex、Claude

3,858,81625,893需要联网MIT通过
vercel-react-native-skills

Vercel React native skills 前端 · Codex、Claude

2,468,66425,878只读MIT通过
adapt

adapt 搜索 · Codex、Claude

2,027,04023,125操作浏览器未明确通过
bolder

bolder 分析 · Codex、Claude

2,004,28823,130只读未明确通过
tanstack-query

tanstack 查询 · 本页

64212调用外部服务未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

TanStack Query Core Knowledge

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: tanstack-query for comprehensive documentation.

Setup

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60,  // 1 minute
      retry: 1,
    },
  },
});

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <MyApp />
    </QueryClientProvider>
  );
}

Queries

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

function UserProfile({ userId }: { userId: string }) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetchUser(userId),
  });

  if (isLoading) return <Spinner />;
  if (error) return <Error message={error.message} />;
  return <div>{data.name}</div>;
}

// With options
const { data } = useQuery({
  queryKey: ['users', { status: 'active' }],
  queryFn: () => fetchUsers({ status: 'active' }),
  staleTime: 5 * 60 * 1000,
  refetchOnWindowFocus: false,
  enabled: !!userId,  // Conditional fetch
});

Mutations

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

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

  const mutation = useMutation({
    mutationFn: (newUser: CreateUserInput) => createUser(newUser),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
    },
  });

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      mutation.mutate({ name: 'John' });
    }}>
      <button disabled={mutation.isPending}>
        {mutation.isPending ? 'Creating...' : 'Create'}
      </button>
    </form>
  );
}

Optimistic Updates

const mutation = useMutation({
  mutationFn: updateUser,
  onMutate: async (newData) => {
    await queryClient.cancelQueries({ queryKey: ['user', id] });
    const previous = queryClient.getQueryData(['user', id]);
    queryClient.setQueryData(['user', id], newData);
    return { previous };
  },
  onError: (err, newData, context) => {
    queryClient.setQueryData(['user', id], context.previous);
  },
  onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ['user', id] });
  },
});

When NOT to Use This Skill

ScenarioUse Instead
Client-side UI state (modals, form inputs)zustand or React state
Vue 3 applicationspinia with custom composables
Static configuration dataReact Context API
Real-time WebSocket dataCustom hooks with WebSocket + Zustand
GraphQL queries@apollo/client or urql

Anti-Patterns

Anti-PatternWhy It's BadCorrect Approach
Using queries for client stateUnnecessary complexity, wrong abstractionUse Zustand or React state
Not using query keys properlyCache collisions, wrong dataUse query key factory pattern
Fetching on every renderPerformance issuesSet proper staleTime and gcTime
Manual cache invalidation everywhereHard to maintainUse mutation's onSuccess with invalidateQueries
Ignoring loading/error statesPoor UXAlways handle isLoading and error
Using refetch() instead of invalidate()Bypasses cache, wastes requestsUse invalidateQueries() for revalidation
Not prefetching predictable navigationSlow perceived performancePrefetch on hover/mount
Storing queries in global stateDefeats TanStack Query purposeLet TanStack Query manage cache
No retry strategy for transient errorsFailed requests on network blipsConfigure retry with backoff
Missing query key dependenciesStale data when params changeInclude all variables in query key

Quick Troubleshooting

IssueCauseSolution
Queries not refetchingstaleTime too high or enabled: falseLower staleTime or check enabled condition
"No QueryClient set" errorMissing QueryClientProviderWrap app with <QueryClientProvider client={queryClient}>
Mutations not updating UINot invalidating queriesCall queryClient.invalidateQueries() in onSuccess
Infinite refetch loopQuery key changes on every renderStabilize query key with useMemo or constants
SSR hydration mismatchServer/client data out of syncUse HydrationBoundary with dehydrated state
Memory leaksQueries never garbage collectedSet proper gcTime (default 5 minutes)
Optimistic update reverted incorrectlyContext not returned from onMutateReturn previous value from onMutate, restore in onError
Multiple identical requestsNo deduplication intervalSet dedupingInterval in query options

Production Readiness

Query Client Configuration

// lib/queryClient.ts
import { QueryClient, QueryCache, MutationCache } from '@tanstack/react-query';

export const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: (error, query) => {
      // Global error handling for queries
      if (query.state.data !== undefined) {
        // Only show error toasts for background refetch failures
        toast.error(`Background update failed: ${error.message}`);
      }

      // Log to monitoring
      logError({ type: 'query', key: query.queryKey, error });
    },
  }),
  mutationCache: new MutationCache({
    onError: (error, _variables, _context, mutation) => {
      logError({ type: 'mutation', key: mutation.options.mutationKey, error });
    },
  }),
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60, // 1 minute
      gcTime: 1000 * 60 * 5, // 5 minutes (formerly cacheTime)
      retry: (failureCount, error) => {
        // Don't retry on 4xx errors
        if (error.status >= 400 && error.status < 500) return false;
        return failureCount < 3;
      },
      refetchOnWindowFocus: process.env.NODE_ENV === 'production',
    },
    mutations: {
      retry: false,
    },
  },
});

Query Key Factory

// lib/queryKeys.ts - Organized query keys
export const queryKeys = {
  users: {
    all: ['users'] as const,
    lists: () => [...queryKeys.users.all, 'list'] as const,
    list: (filters: UserFilters) => [...queryKeys.users.lists(), filters] as const,
    details: () => [...queryKeys.users.all, 'detail'] as const,
    detail: (id: string) => [...queryKeys.users.details(), id] as const,
  },
  posts: {
    all: ['posts'] as const,
    byUser: (userId: string) => [...queryKeys.posts.all, 'user', userId] as const,
  },
} as const;

// Usage
const { data } = useQuery({
  queryKey: queryKeys.users.detail(userId),
  queryFn: () => fetchUser(userId),
});

// Invalidate all user queries
queryClient.invalidateQueries({ queryKey: queryKeys.users.all });

Error Handling

// hooks/useApiQuery.ts
import { UseQueryOptions, useQuery } from '@tanstack/react-query';

interface ApiError {
  status: number;
  message: string;
}

export function useApiQuery<TData>(
  options: UseQueryOptions<TData, ApiError>
) {
  return useQuery({
    ...options,
    throwOnError: (error) => {
      // Only throw for critical errors that should trigger error boundary
      return error.status >= 500;
    },
  });
}

// With error boundary
function UserProfile({ userId }: { userId: string }) {
  const { data, error, isLoading } = useApiQuery({
    queryKey: queryKeys.users.detail(userId),
    queryFn: () => fetchUser(userId),
  });

  if (isLoading) return <Skeleton />;

  if (error) {
    if (error.status === 404) return <NotFound />;
    return <ErrorMessage message={error.message} />;
  }

  return <UserCard user={data} />;
}

Prefetching & SSR

// Next.js App Router example
// app/users/page.tsx
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';

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

  await queryClient.prefetchQuery({
    queryKey: queryKeys.users.lists(),
    queryFn: fetchUsers,
  });

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <UserList />
    </HydrationBoundary>
  );
}

// Prefetch on hover
function UserLink({ userId }: { userId: string }) {
  const queryClient = useQueryClient();

  const prefetchUser = () => {
    queryClient.prefetchQuery({
      queryKey: queryKeys.users.detail(userId),
      queryFn: () => fetchUser(userId),
      staleTime: 1000 * 60,
    });
  };

  return (
    <Link href={`/users/${userId}`} onMouseEnter={prefetchUser}>
      View User
    </Link>
  );
}

Testing

// test-utils.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const createTestQueryClient = () =>
  new QueryClient({
    defaultOptions: {
      queries: { retry: false, gcTime: 0 },
      mutations: { retry: false },
    },
  });

export function renderWithQuery(ui: React.ReactElement) {
  const queryClient = createTestQueryClient();
  return {
    ...render(
      <QueryClientProvider client={queryClient}>
        {ui}
      </QueryClientProvider>
    ),
    queryClient,
  };
}

// Test example
test('displays user data', async () => {
  server.use(
    http.get('/api/users/:id', () => {
      return HttpResponse.json({ id: '1', name: 'John' });
    })
  );

  renderWithQuery(<UserProfile userId="1" />);

  expect(await screen.findByText('John')).toBeInTheDocument();
});

Monitoring Metrics

MetricTarget
Cache hit ratio> 80%
Average query time< 200ms
Stale data served< 5%
Background refetch errors< 1%

Checklist

  • Query key factory pattern
  • Global error handling in QueryCache
  • Retry logic for transient failures
  • staleTime and gcTime configured
  • Optimistic updates for mutations
  • Prefetching for navigation
  • SSR hydration setup
  • Test utilities with fresh QueryClient
  • DevTools in development only
  • Error boundaries for critical failures

OpenAPI Integration

TanStack Query works seamlessly with generated OpenAPI clients for type-safe data fetching.

With Generated Types

import type { paths, components } from '@/types/api';
import { useQuery, useMutation } from '@tanstack/react-query';

type User = components['schemas']['User'];
type CreateUserInput = components['schemas']['CreateUserInput'];

// Type-safe query
function useUser(id: string) {
  return useQuery<User>({
    queryKey: ['users', id],
    queryFn: async () => {
      const res = await fetch(`/api/users/${id}`);
      return res.json();
    },
  });
}

// Type-safe mutation
function useCreateUser() {
  return useMutation<User, Error, CreateUserInput>({
    mutationFn: async (input) => {
      const res = await fetch('/api/users', {
        method: 'POST',
        body: JSON.stringify(input),
      });
      return res.json();
    },
  });
}

With openapi-fetch

import createClient from 'openapi-fetch';
import type { paths } from '@/types/api';

const api = createClient<paths>({ baseUrl: '/api' });

function useUsers() {
  return useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const { data, error } = await api.GET('/users');
      if (error) throw error;
      return data;
    },
  });
}

Related Skills

SkillPurpose
OpenAPI CodegenGenerate types from spec
HTTP ClientsAxios/fetch integration
React APIAlternative patterns (SWR)

Reference Documentation

平台分布

Codex

35.74%
按下载量换算80

Claude

28.17%
按下载量换算63

Cursor

21.06%
按下载量换算47

Gemini CLI

9.13%
按下载量换算21

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

调用外部服务

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills