Skip to main content

TanStack Query fundamentals and cache

This handbook targets TanStack Query 5.101.4.

TanStack Query is a server-state library: it helps React applications fetch, cache, synchronize, and update asynchronous remote data.

Server state is different from client state​

Client state vs server state
Client state

Dialog open Β· selected tab Β· editor tool Β· unsaved draft.

The client owns the authoritative value.

Server state

Products Β· orders Β· account profile Β· inventory.

The server remains authoritative.

The client does not own the authoritative version of server state.

Server state introduces:

  • freshness;
  • staleness;
  • caching;
  • refetching;
  • retries;
  • invalidation;
  • background synchronization;
  • pagination;
  • mutation reconciliation.

Install​

npm install @tanstack/react-query

Create a QueryClient​

import {
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'

const queryClient = new QueryClient()

root.render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>,
)

Mental model:

QueryClient architecture
QueryClient

Owns cache state and policies.

Query cache
Mutation cache
Defaults / policies
React query observers

Basic query​

import { useQuery } from '@tanstack/react-query'

async function getProducts(): Promise<Product[]> {
const response = await fetch('/api/products')

if (!response.ok) {
throw new Error('Failed to load products')
}

return response.json()
}

function ProductList() {
const productsQuery = useQuery({
queryKey: ['products'],
queryFn: getProducts,
})

if (productsQuery.isPending) {
return <p>Loading products…</p>
}

if (productsQuery.isError) {
return <p>Could not load products.</p>
}

return (
<ul>
{productsQuery.data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}

Query key = cache identity​

Current TanStack Query v5 query keys are arrays at the top level.

['products']
['product', productId]
['orders', { status, page }]
Query key defines cache identity
queryKey
Resource + every parameter used by the query.
One cache entry
Stable identity for that remote resource snapshot.
Observers using the same key
Components observe the same cached query identity.

If the query function depends on a variable, include that variable in the key.

useQuery({
queryKey: ['product', productId],
queryFn: () => getProduct(productId),
})

Query key factories​

For larger applications, create consistent key helpers.

export const productKeys = {
all: ['products'] as const,
lists: () => [...productKeys.all, 'list'] as const,
list: (filters: ProductFilters) =>
[...productKeys.lists(), filters] as const,
detail: (id: string) =>
[...productKeys.all, 'detail', id] as const,
}

This reduces accidental cache-key drift.

Fresh vs stale​

One of the most important TanStack Query concepts is freshness.

1query fetched
2fresh during staleTime
3becomes stale
4eligible for background refetch

By default, query data is considered stale immediately unless you configure staleTime.

useQuery({
queryKey: ['products'],
queryFn: getProducts,
staleTime: 60_000,
})

This means the data remains fresh for one minute.

Fresh does not mean "permanently correct." It means TanStack Query should not consider the cached data stale during that period.

Cache lifetime is separate from freshness​

staleTime and gcTime answer different questions
staleTime

When should cached data be considered stale?

This is a freshness policy.

gcTime

How long should an unused cache entry remain before garbage collection?

This is a retention policy.

Do not confuse freshness with cache retention.

Important defaults​

TanStack Query's defaults are intentionally active.

Key ideas include:

  • cached query data is stale by default;
  • stale queries can refetch when observers mount or environment triggers occur under policy;
  • failed queries retry by default in common client usage;
  • inactive queries stay cached until garbage collection policy removes them.

Know the defaults before diagnosing "unexpected extra requests."

Deduplication through cache identity​

Two components using the same query key are observing the same cached query identity.

Two observers, one cache identity
Header
Uses ['user', 42].
ProfilePage
Uses ['user', 42].
Shared cache entry

Both observers read the same query identity instead of independently rebuilding fetch state.

This is fundamentally different from both components independently using useEffect(fetch...).

Query function errors​

A query function should reject/throw when the operation fails.

fetch does not reject merely because the response status is 404/500, so check response.ok yourself when using fetch directly.

Query cancellation​

TanStack Query provides an AbortSignal to query functions.

async function getProduct({ signal }: QueryFunctionContext) {
const response = await fetch('/api/product', { signal })
// ...
}

Use cancellation when your data source supports it and aborting obsolete work is meaningful.

Dependent queries​

Sometimes query B cannot run until query A provides an identifier.

const userQuery = useQuery({
queryKey: ['user', email],
queryFn: () => getUser(email),
})

const projectsQuery = useQuery({
queryKey: ['projects', userQuery.data?.id],
queryFn: () => getProjects(userQuery.data!.id),
enabled: Boolean(userQuery.data?.id),
})

Be careful: dependent queries can create request waterfalls.

If requests can run in parallel, prefer parallel architecture.

TanStack Query vs useEffect​

Manual effect fetching often becomes:

Manual Effect fetching can grow into a cache system
useEffect(fetch...)

Loading + error + race handling + cleanup + retry + caching + refetch + invalidation.

TanStack Query centralizes that server-state lifecycle.

Effects still have valid synchronization uses. The point is not "never fetch in an Effect"; it is to recognize when you are rebuilding a cache system.

TanStack Query vs Redux/Zustand​

Different ownership categories
Redux / Zustand
Client-owned shared state.
TanStack Query
Remote/server-owned state lifecycle.

A real application may use both.

Debugging​

When data appears "wrong," ask:

  1. What is the query key?
  2. Is every query-function variable represented in that key?
  3. Is the data fresh or stale?
  4. Is an observer mounted?
  5. Which refetch trigger occurred?
  6. Was the query invalidated?
  7. Are two resources accidentally sharing a key?
  8. Is the server actually returning stale data?

Use TanStack Query Devtools during development when useful.

Exercise​

Build a product catalogue with:

  • ['products', filters] list queries;
  • ['product', id] detail queries;
  • loading and error UI;
  • a one-minute staleTime for product details;
  • a documented key factory.

Then explain when two components share the same cached data.

Interview questions​

Junior: What do queryKey and queryFn represent?

Mid-level: What is the difference between stale data and garbage-collected cache data?

Senior: Why can dependent queries create waterfalls?

Staff: How would you design query-key ownership across many teams so invalidation remains predictable?

References​