Skills2026年4月11日·1 分钟阅读

TanStack Query — Async State & Data Fetching for the Web

TanStack Query (formerly React Query) is a powerful asynchronous state management library for TS/JS that handles server-state, caching, background updates, and data synchronization across React, Solid, Svelte, and Vue.

Agent 就绪

先审查再安装

这个资产需要先审查。复制的指令会要求 Agent dry-run、列出写入项,确认后再继续。

Needs Confirmation · 64/100策略:需确认
Agent 入口
任意 MCP/CLI Agent
类型
Skill
安装
Single
信任
信任等级:Established
入口
step-1.md
先审查命令
npx -y tokrepo@latest install 26726f79-355f-11f1-9bc6-00163e2b0d79 --target codex

先 dry-run,确认写入项后再运行此命令。

TL;DR
TanStack Query manages server state, caching, and background refetching across React, Vue, Solid, and Svelte.
§01

What it is

TanStack Query (formerly React Query) is an asynchronous state management library for TypeScript and JavaScript. It handles server-state caching, background updates, stale data revalidation, and data synchronization across React, Solid, Svelte, and Vue applications.

Frontend developers who fetch data from APIs and struggle with loading states, cache invalidation, and background refetching will find TanStack Query eliminates most of that boilerplate.

§02

How it saves time or tokens

TanStack Query replaces custom useEffect + useState patterns for data fetching with a declarative API. It handles caching, deduplication, retries, and window focus refetching automatically. Developers write fewer lines of code and avoid common bugs like race conditions and stale closures.

§03

How to use

  1. Install @tanstack/react-query (or the adapter for your framework).
  2. Wrap your app in a QueryClientProvider.
  3. Use useQuery to fetch data and useMutation to modify it.
import { useQuery } from '@tanstack/react-query';

function UserProfile({ userId }: { userId: string }) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error loading user</div>;
  return <h1>{data.name}</h1>;
}
§04

Example

Automatic cache invalidation after a mutation:

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

const queryClient = useQueryClient();
const mutation = useMutation({
  mutationFn: (newUser) => fetch('/api/users', {
    method: 'POST', body: JSON.stringify(newUser)
  }),
  onSuccess: () => queryClient.invalidateQueries({ queryKey: ['users'] }),
});
§05

Related on TokRepo

§06

Common pitfalls

  • Query keys must be serializable and unique. Inconsistent keys cause cache misses and duplicate requests.
  • Over-fetching with too many queries on a single page can degrade performance. Use select to pick only needed fields.
  • Stale time defaults to 0, meaning data is always considered stale. Adjust staleTime to reduce unnecessary refetches.

常见问题

Is TanStack Query only for React?+

No. TanStack Query supports React, Solid, Svelte, and Vue through separate adapter packages. The core caching and state management logic is framework-agnostic.

What is the difference between staleTime and gcTime?+

staleTime controls how long data is considered fresh (no refetch needed). gcTime (formerly cacheTime) controls how long inactive query data stays in memory before garbage collection. They serve different purposes.

Does TanStack Query replace Redux?+

TanStack Query replaces Redux for server-state management (API data). If you have client-only state (UI toggles, form state), you may still need a client state manager like Zustand or Redux.

How does TanStack Query handle errors?+

Queries automatically retry failed requests (3 times by default). You can customize retry count, delay, and error handling via the query configuration or global defaults on the QueryClient.

Can I use TanStack Query with SSR?+

Yes. TanStack Query supports server-side rendering with hydration. Prefetch queries on the server, dehydrate the cache, and hydrate it on the client to avoid double-fetching.

引用来源 (3)

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产