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.
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.
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.
How to use
- Install
@tanstack/react-query(or the adapter for your framework). - Wrap your app in a
QueryClientProvider. - Use
useQueryto fetch data anduseMutationto 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>;
}
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'] }),
});
Related on TokRepo
- AI coding tools — Tools and libraries for modern development
- Featured workflows — Discover popular developer tools and workflows
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
selectto pick only needed fields. - Stale time defaults to 0, meaning data is always considered stale. Adjust
staleTimeto reduce unnecessary refetches.
Frequently Asked Questions
No. TanStack Query supports React, Solid, Svelte, and Vue through separate adapter packages. The core caching and state management logic is framework-agnostic.
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.
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.
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.
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.
Citations (3)
- TanStack Query GitHub— TanStack Query handles server-state caching and background updates
- TanStack Query Documentation— Supports React, Solid, Svelte, and Vue frameworks
- TanStack Query Guide— Automatic caching, deduplication, and window focus refetching
Related on TokRepo
Discussion
Related Assets
NAPI-RS — Build Node.js Native Addons in Rust
Write high-performance Node.js native modules in Rust with automatic TypeScript type generation and cross-platform prebuilt binaries.
Mamba — Fast Cross-Platform Package Manager
A drop-in conda replacement written in C++ that resolves environments in seconds instead of minutes.
Plasmo — The Browser Extension Framework
Build, test, and publish browser extensions for Chrome, Firefox, and Edge using React or Vue with hot-reload and automatic manifest generation.