Features
- Automatic caching and cache invalidation
- Background refetching and stale-while-revalidate
- Optimistic updates for instant UI feedback
- Infinite scroll and paginated queries
- Framework-agnostic (React, Vue, Svelte, Solid, Angular)
Pros
- Eliminates boilerplate for async data fetching
- Powerful cache management with fine-grained control
- Excellent DevTools for debugging queries
- Multi-framework support
Cons
- Adds complexity for simple data fetching needs
- Cache invalidation requires careful planning
- Not suited for client-only state management
Overview
TanStack Query (formerly React Query) is an async state management library that handles fetching, caching, synchronizing, and updating server state in web applications. It separates server state (data from APIs) from client state (UI state), providing a purpose-built solution for the most common type of state in modern applications.
TanStack Query automatically handles caching, deduplication, background refetching, stale data management, pagination, and optimistic updates. Its declarative API replaces complex state management code with simple hooks that describe what data a component needs, while the library handles when and how to fetch it.
When to Use
TanStack Query is the right choice for any application that fetches data from APIs. It’s not a replacement for client-side state management (use Zustand or Jotai for that) but rather a complement that handles all server state concerns. Most applications benefit from pairing TanStack Query with a lightweight client state library.
Getting Started
npm install @tanstack/react-query
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 <p>Loading...</p>;
if (error) return <p>Error loading user</p>;
return <h1>{data.name}</h1>;
}