TanStack Query: Server State & Asynchronous Cache Architecture
TanStack Query (Cache): Automate server data fetching, background refetching, deduplication, and cache invalidation.
One of the most consequential shifts in modern React is recognizing that client state and server state are fundamentally different beasts:
- **Client state:** Synchronous, ephemeral, and strictly local to the browser session (e.g., whether a sidebar is expanded, a theme switch, or an active step in a wizard).
- **Server state:** Asynchronous, persisted remotely in a database, shared across multiple devices/users, and not owned by the client. The browser merely holds an out-of-date snapshot that begins decaying the moment it arrives over the wire.
- Trying to manage server state with client primitives—like tying useEffect to useState or stuffing API responses into Redux or Zustand—introduces a massive maintenance tax: manual loading and error booleans, race conditions on rapid navigation, stale data accumulation, and bespoke caching bugs.
TanStack Query (React Query) is not a data-fetching library; it delegates actual HTTP transfers to fetch, axios, or GraphQL clients. Instead, it is an asynchronous state synchronizer and cache manager that automates request deduplication, background synchronization, memory garbage collection, and optimistic mutations.
## 1. Core Architecture: How the Query Cache Works
```text
At the foundation of TanStack Query are the QueryClient and its internal QueryCache. Every active or stored query is identified by a deterministic, serializable Query Key.
Component A [useQuery({ queryKey: ['users', 1] })] ──┐
├──► [ QueryCache ] ──► Single HTTP Request
Component B [useQuery({ queryKey: ['users', 1] })] ──┘ (Deduplicated!)
```
### 1.1 Request Deduplication
When three separate components on the same view run useQuery using the identical key ['users', 1] at the same moment, TanStack Query:
- Detects an active promise already in flight for that key.
- Fires exactly one network request.
- Broadcasts the resolved payload to all three components at the same instant.
### 1.2 The "Stale-While-Revalidate" Lifecycle
TanStack Query mirrors the HTTP stale-while-revalidate caching model to balance perceived speed with data freshness:
```text
Cached Data Available?
├─► NO: isPending = true ──► Fetch from Network ──► Paint Data
└─► YES: Immediately render CACHED data (zero spinner flicker!)
│
├─► Is data "fresh" (staleTime has not expired)?
│ └─► Do nothing.
│
└─► Is data "stale" (staleTime expired)?
└─► Trigger Background Refetch (isFetching = true)
│
└─► Response returns ──► Silently swap in fresh data
```
## 2. Key Lifecycle Configurations: staleTime vs. gcTime
The interplay between staleTime and gcTime (renamed from cacheTime in v5) trips up many developers:
| Dimension | staleTime | gcTime (Garbage Collection Time) |
| --- | --- | --- |
| What it governs | How long fetched data is considered fresh before needing revalidation. | How long inactive, unmounted data lingers in memory before being purged. |
| Default value | 0 (data is marked stale immediately upon arrival). | 5 * 60 * 1000 (5 minutes). |
| Component mount behavior | If expired, triggers a silent background refetch. | If expired, cache memory is wiped; the query falls back to a hard loading state. |
| Real-world analogy | The "best before" date stamped on an item. | How long an unused item sits on a shelf before being thrown in the dumpster. |
### Practical Configuration
```ts
// Rapidly updating data: financial ticker
useQuery({
queryKey: ['ticker', 'AAPL'],
queryFn: fetchStockPrice,
staleTime: 5 * 1000, // Fresh for 5 seconds; revalidates frequently
gcTime: 10 * 60 * 1000, // Retain in memory for 10 minutes if user navigates away
});
// Infrequently changing data: static documentation/FAQ
useQuery({
queryKey: ['site-faqs'],
queryFn: fetchFaqs,
staleTime: 60 * 60 * 1000, // Fresh for 1 hour; skips unnecessary background fetches
gcTime: 2 * 60 * 60 * 1000, // Keep alive in cache for 2 hours
});
```
## 3. Query Keys as Deterministic Dependency Arrays
Query keys work just like the dependency arrays in useEffect. Whenever a primitive, object, or variable inside a key changes, TanStack Query automatically transitions to and manages the new key.
### 3.1 Hierarchical Array Conventions
Structure keys hierarchically—moving from broad domain entities down to granular filters:
```ts
// Broad domain entity
['todos']
// Filtered / paginated sub-collection
['todos', { status: 'completed', page: 2 }]
// Granular resource instance
['todos', 'detail', todoId]
```
### 3.2 The Query Key Factory Pattern
Scattering raw string arrays across a codebase creates subtle typo bugs and broken cache invalidations. Using a Query Key Factory centralizes key creation:
```ts
// src/features/users/userQueryKeys.ts
export const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
list: (filters: { role?: string; search?: string }) =>
[...userKeys.lists(), filters] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: string) => [...userKeys.details(), id] as const,
};
// Usage inside a hook:
useQuery({
queryKey: userKeys.list({ role: 'admin' }),
queryFn: () => fetchUsers({ role: 'admin' }),
});
// Coarse invalidation: invalidates EVERY query under ['users']
queryClient.invalidateQueries({ queryKey: userKeys.all });
// Surgical invalidation: invalidates only a specific user's detail record
queryClient.invalidateQueries({ queryKey: userKeys.detail('usr_123') });
```
## 4. Built-in Background Triggers
Instead of writing interval loops, TanStack Query synchronizes data automatically based on real-world browser events:
- **refetchOnWindowFocus (default:** true): Refetches stale queries when the user tabs back to your application.
- **refetchOnReconnect (default:** true): Refetches stale queries immediately when network connectivity drops and recovers.
- **refetchOnMount (default:** true): Triggers a background refresh whenever a component mounts with stale cache data.
## 5. Mutation Lifecycle & Cache Invalidation
While useQuery handles reads, useMutation handles asynchronous writes (POST, PUT, DELETE, PATCH).
### Declarative Invalidation
Instead of manually splicing items into local arrays after a mutation succeeds, invalidate the matching query key so TanStack Query pulls the source of truth fresh from the server:
```ts
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { userKeys } from './userQueryKeys';
export function CreateUserForm() {
const queryClient = useQueryClient();
const { mutate, isPending, error } = useMutation({
mutationFn: async (newUserData: { name: string; email: string }) => {
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUserData),
});
if (!res.ok) throw new Error('Failed to create user');
return res.json();
},
onSuccess: () => {
// Invalidate the collection key to trigger a clean background refetch
queryClient.invalidateQueries({ queryKey: userKeys.lists() });
},
});
return (
);
}
```
## 6. Zero-Latency Optimistic Updates
For interactions where latency feels unacceptable (such as toggling a favorite, completing a task, or hitting a like button), you can update the cache immediately while the request is in flight, rolling back cleanly if the request fails:
```ts
import { useMutation, useQueryClient } from '@tanstack/react-query';
interface Todo {
id: string;
title: string;
completed: boolean;
}
export function useToggleTodo() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (targetTodo: { id: string; completed: boolean }) => {
const res = await fetch(`/api/todos/${targetTodo.id}`, {
method: 'PATCH',
body: JSON.stringify({ completed: targetTodo.completed }),
});
if (!res.ok) throw new Error('Failed to update todo');
return res.json();
},
// 1. Immediately before the mutation fires:
onMutate: async (updatedTodo) => {
// Abort in-flight queries so they don't overwrite our optimistic update
await queryClient.cancelQueries({ queryKey: ['todos'] });
// Take a snapshot of the current state for rollback purposes
const previousTodos = queryClient.getQueryData(['todos']);
// Optimistically write the updated value into the cache
queryClient.setQueryData(['todos'], (old = []) =>
old.map((todo) =>
todo.id === updatedTodo.id ? { ...todo, completed: updatedTodo.completed } : todo
)
);
// Pass the snapshot downstream in context
return { previousTodos };
},
// 2. If the request encounters an error:
onError: (_err, _updatedTodo, context) => {
// Restore previous state from snapshot
if (context?.previousTodos) {
queryClient.setQueryData(['todos'], context.previousTodos);
}
},
// 3. Always refetch regardless of outcome to guarantee server truth
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] });
},
});
}
```
## 7. Transforming Derived State via select
When a component only depends on a subset or transformed version of a cached dataset, use the select option. TanStack Query memoizes the transformation and ensures the consuming component only re-renders if the derived result changes:
```ts
export function useCompletedTodosCount() {
return useQuery({
queryKey: ['todos'],
queryFn: fetchTodos,
// Component re-renders ONLY when the count changes, not on every todo field update
select: (todos) => todos.filter((t) => t.completed).length,
});
}
```
