Scripts2026年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.

SC
Script Depot · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

npm i @tanstack/react-query
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";

const qc = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={qc}>
      <Todos />
    </QueryClientProvider>
  );
}

function Todos() {
  const { data, isLoading } = useQuery({
    queryKey: ["todos"],
    queryFn: () => fetch("/api/todos").then(r => r.json()),
  });
  if (isLoading) return <p>Loading...</p>;
  return <ul>{data.map(t => <li key={t.id}>{t.title}</li>)}</ul>;
}
介绍

TanStack Query (formerly React Query) is the missing data-fetching library for web applications. It eliminates manual state management for server data (loading/error/caching/refetch).

What TanStack Query Does

  • Caching — automatic with configurable staleTime/gcTime
  • Deduping — identical requests collapsed
  • Background refetch — on window focus, reconnect, interval
  • Pagination/Infinite queries — first-class support
  • Mutations — optimistic updates with rollback
  • Devtools — inspect cache state in real time

Architecture

Singleton QueryClient holds the cache. Each useQuery subscribes via queryKey. Cache invalidation uses key prefix matching: queryClient.invalidateQueries({ queryKey: ["todos"] }).

Self-Hosting

No backend. Client-only library. Install via package manager.

Key Features

  • Framework-agnostic core
  • Typed queries (infer from queryFn)
  • Optimistic updates
  • Parallel & dependent queries
  • Prefetching & SSR support (Next.js, Remix, Nuxt)
  • Offline support
  • Automatic retries with exponential backoff

Comparison

Library Scope Mutations Caching
TanStack Query Server state Yes Automatic
SWR Server state Limited Automatic
Redux Toolkit Query Server state Yes Manual tags
Apollo Client GraphQL Yes Normalized

常见问题 FAQ

Q: 和 Redux 冲突吗? A: 不。Redux 管 client state,Query 管 server state。组合使用。

Q: staleTime 和 gcTime 区别? A: staleTime 决定数据多久变为 stale(触发后台 refetch);gcTime 决定未订阅数据多久从 cache 删除。

Q: 支持 SSR 吗? A: 支持。用 HydrationBoundary + dehydrate 在服务端预取。

来源与致谢 Sources

讨论

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

相关资产