Client-side Caching in React with TanStack Query
Master client-side server-state caching in React: staleTime vs gcTime, request deduplication, cache invalidation, and optimistic updates.
When building modern React applications, developers inevitably encounter a recurring dilemma: “Once the API has returned data, do subsequent components or page visits need to fetch it all over again?”
Consider a scenario with an endpoint GET /api/users/123. A navigation bar component needs the user’s avatar, a profile card needs their name, and an activity feed needs their account details.
Header Component ──→ GET /api/users/123
Profile Component ──→ GET /api/users/123
ActivityFeed Component ──→ GET /api/users/123textIn standard React code relying on useEffect and useState, every mounting component triggers an independent network request. This generates redundant network traffic, causes distracting UI layout shifts with loading spinners, and places needless load on backend services.
[!NOTE] TL;DR:
@tanstack/react-query(formerly React Query) is far more than a convenient replacement forfetch()oraxios. It functions as a Client-Side Server-State Cache, orchestrating data deduplication, automatic background synchronization, cache lifecycle management (staleTimevs.gcTime), and snappy optimistic updates.
1. The Core Problem: The Pitfalls of DIY Caching#
When faced with redundant API calls, a common first instinct is to roll a custom in-memory cache:
const userCache = new Map<number, Promise<User> | User>()
export async function getUser(userId: number): Promise<User> {
if (userCache.has(userId)) {
return userCache.get(userId)!
}
const promise = fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => {
userCache.set(userId, data)
return data
})
userCache.set(userId, promise)
return promise
}typescriptWhile clean on the surface, a simplistic Map() cache quickly spirals into an architectural sinkhole as application complexity grows:
- When does cached data expire? (Stale expiration)
- When should background refetching happen? (Window focus, network reconnect)
- If a user edits their name, how are all listening components notified? (Cache invalidation)
- How are loading states, errors, and retry backoffs managed when networks drop?
- How are race conditions handled when users switch pages rapidly?
- If a user leaves a dashboard idle, does the Map leak memory indefinitely? (Garbage collection)
- How do you support pagination, infinite scrolling, or optimistic mutations?
Attempting to resolve these questions means reinventing 80% of a full-fledged asynchronous state library. This is precisely why TanStack Query exists.
2. Mental Model (ELI5): Server State vs. Client State#
To truly grasp TanStack Query, the most fundamental step is separating your application’s state into two distinct categories.
Explain Like I’m 10 (ELI5)#
- Client State: Imagine your personal notebook lying on your study desk. You decide what to draw, which page to turn to, and what color pen to use. No outside party alters it without your permission. Examples: an open sidebar, a selected theme, or half-typed form inputs.
- Server State: Imagine a book borrowed from a public library. You hold a temporary snapshot. Back at the library, an author or librarian might have already published a revised edition or loaned the original out to someone else.
[!WARNING] Your frontend does not own Server State. The single source of truth resides on the remote server database. Consequently, any API data sitting in client memory is potentially stale from the exact millisecond it arrives.
This explains why storing API data in global stores like Redux or Zustand often feels clunky. Redux and Zustand excel at synchronous client state, whereas TanStack Query is tailored specifically to act as an asynchronous caching mediator for server state.
3. How TanStack Query Caching Operates#
Let us walk through a foundational implementation. First, wrap your React component tree in QueryClientProvider:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { UserProfile } from './UserProfile'
const queryClient = new QueryClient()
export function App() {
return (
<QueryClientProvider client={queryClient}>
<UserProfile userId={123} />
</QueryClientProvider>
)
}tsxNext, consume the query inside your component:
import { useQuery } from '@tanstack/react-query'
interface User {
id: number
name: string
email: string
}
async function fetchUser(userId: number): Promise<User> {
const res = await fetch(`/api/users/${userId}`)
if (!res.ok) throw new Error('Failed to retrieve user')
return res.json()
}
export function UserProfile({ userId }: { userId: number }) {
const { data, isPending, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId),
})
if (isPending) return <div className="skeleton">Loading...</div>
if (error) return <div className="alert-error">Error: {error.message}</div>
return (
<div className="card">
<h2>{data.name}</h2>
<p>{data.email}</p>
</div>
)
}tsxThe queryKey is the Cache Identity#
TanStack Query indexes all cached items within a hash map serialized deterministically from the queryKey array:
['user', 123] ──→ Cache entry A: { id: 123, name: 'John' }
['user', 456] ──→ Cache entry B: { id: 456, name: 'Alice' }
['posts', 123] ──→ Cache entry C: [ ... ]textWhen two independent components across disparate parts of the DOM mount and invoke useQuery with ['user', 123], TanStack Query immediately matches the query key and serves the cached record without redundant fetching.
4. Request Deduplication in Action#
Consider a common scenario: a dashboard page mounts three distinct sibling components that all request profile information for the authenticated user:
Rather than firing three duplicate HTTP calls over the network wire, TanStack Query groups these concurrent calls by their identical queryKey. A single network promise is dispatched, and upon fulfillment, the data is distributed instantaneously across all subscribers.
5. staleTime vs. gcTime: Demystifying the Confusion#
The distinction between staleTime and gcTime is one of the most frequently misunderstood mechanics in TanStack Query.
| Option | Former Name | Operational Definition | Default Value |
|---|---|---|---|
staleTime | staleTime | How long is retrieved data considered fresh before transitioning to stale? | 0 ms |
gcTime | cacheTime | How long does unmounted (inactive) data persist in memory before being Garbage Collected? | 5 * 60 * 1000 (5 minutes) |
00s: API Fetch Completes ──────→ Data is Fresh
│
│ (During staleTime: newly mounted components read cache without refetching)
▼
60s: staleTime Expires ────────→ Data becomes Stale (still retained in cache!)
│
│ (User navigates away; all components using ['users'] unmount)
▼
70s: Query becomes Inactive ───→ gcTime countdown initiates (5 minutes)
│
▼
370s: gcTime Expires ──────────→ Cache record purged from JavaScript memorytext[!TIP] Golden Rule: Setting
staleTime: 60000does NOT mean data is deleted after 60 seconds. It simply marks the data as stale. TanStack Query embraces the Stale-While-Revalidate pattern: when a user revisits, stale data is rendered immediately so the UI is never blank, while an invisible background refetch confirms whether new data exists.
Practical Setup for Static or Catalog Data#
For relatively immutable data (e.g., country dropdowns, tax rates, category lists):
export const categoriesQueryOptions = {
queryKey: ['categories'],
queryFn: fetchCategories,
staleTime: 10 * 60 * 1000, // Considered fresh for 10 minutes
gcTime: 60 * 60 * 1000, // Retained in memory for 60 minutes when inactive
}typescript6. The Trade-Off: Performance vs. Freshness#
Client-side caching inherently balances two opposing forces:
Maximum Performance (Fewer Requests) ◄───────────► Immediate Freshness (Real-time)
High staleTime staleTime = 0textIf the server updates a record from "John" to "Mike", but your client query holds a staleTime of 10 minutes, the browser displays "John" until either the timer expires or a synchronization trigger occurs.
To maintain near real-time accuracy without invasive code, TanStack Query introduces automated background refetch hooks:
refetchOnWindowFocus(default:true): When users switch back from another browser tab, stale queries automatically refresh.refetchOnReconnect(default:true): Re-syncs queries when network connectivity recovers.refetchOnMount(default:true): Revalidates queries on mount if existing cached data is stale.
7. Data Mutations & Cache Invalidation#
When executing mutating operations (POST, PUT, DELETE), leverage useMutation paired with queryClient.invalidateQueries.
Here is a standard production pattern:
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
export function UserManagement() {
const queryClient = useQueryClient()
// 1. Fetch collection
const { data: users, isPending } = useQuery({
queryKey: ['users'],
queryFn: async () => {
const res = await fetch('/api/users')
return res.json()
},
staleTime: 60_000,
})
// 2. Mutation for creation
const addMutation = useMutation({
mutationFn: async (newUser: { name: string }) => {
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUser),
})
if (!res.ok) throw new Error('Failed to create user')
return res.json()
},
onSuccess: () => {
// Invalidate all queries beginning with ['users']
queryClient.invalidateQueries({ queryKey: ['users'] })
},
})
if (isPending) return <div>Loading users...</div>
return (
<div>
<ul>
{users?.map((u: { id: number; name: string }) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
<button
type="button"
disabled={addMutation.isPending}
onClick={() => addMutation.mutate({ name: 'Alex' })}
>
{addMutation.isPending ? 'Saving...' : 'Add User'}
</button>
</div>
)
}tsx8. Instant Feedback: Optimistic Updates#
For high-frequency interactions like toggling a bookmark or liking a post, waiting 400ms for server roundtrips harms perceived responsiveness.
Optimistic Updates modify client state immediately, trigger the backend request asynchronously, and automatically rollback to a saved snapshot if the network call fails:
import { useMutation, useQueryClient } from '@tanstack/react-query'
interface Post {
id: number
title: string
likes: number
}
export function useLikePost(postId: number) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async () => {
const res = await fetch(`/api/posts/${postId}/like`, { method: 'POST' })
if (!res.ok) throw new Error('Like failed')
return res.json()
},
onMutate: async () => {
// 1. Cancel in-flight refetches so they don't overwrite optimistic data
await queryClient.cancelQueries({ queryKey: ['post', postId] })
// 2. Snapshot current state for rollback protection
const previousPost = queryClient.getQueryData<Post>(['post', postId])
// 3. Optimistically increment likes in local cache
queryClient.setQueryData<Post>(['post', postId], (old) => {
if (!old) return old
return { ...old, likes: old.likes + 1 }
})
// 4. Provide snapshot context to error handler
return { previousPost }
},
onError: (_err, _variables, context) => {
// Rollback to prior state if mutation errors out
if (context?.previousPost) {
queryClient.setQueryData(['post', postId], context.previousPost)
}
},
onSettled: () => {
// Always re-sync with remote truth upon completion
queryClient.invalidateQueries({ queryKey: ['post', postId] })
},
})
}tsx9. Comparing TanStack Query vs. HTTP Browser Cache#
A frequent inquiry arises: “Since modern browsers provide HTTP Caching via Cache-Control and ETag, why introduce TanStack Query?”
They operate at two distinct architectural tiers:
| Dimension | TanStack Query | HTTP Browser Cache |
|---|---|---|
| Storage Location | JavaScript Heap Memory | Browser Disk / Network Cache |
| Component Awareness | Fully aware of React lifecycle (mount, unmount, focus) | Purely handles URLs, HTTP verbs, and headers |
| UI Reactivity | Triggers reactive re-renders when data updates | Completely decoupled from DOM rendering |
| Request Deduplication | Shares single active promise across components | May fire parallel requests if triggered simultaneously |
| Mutations & Rollback | First-class optimistic updates and targeted invalidation | None |
These layers complement each other: HTTP Caching saves bandwidth (using 304 Not Modified headers), while TanStack Query guarantees a seamless, reactive user interface.
10. Scalable Architecture: The Query Key Factory Pattern#
In large codebases, scattering ad-hoc arrays like ['users', id, 'posts'] leads to typos and unpredictable cache invalidation.
Adopt the Query Key Factory pattern:
export const userKeys = {
all: ['users'] as const,
lists: () => [...userKeys.all, 'list'] as const,
list: (filters: { page: number; search?: string }) =>
[...userKeys.lists(), filters] as const,
details: () => [...userKeys.all, 'detail'] as const,
detail: (id: number) => [...userKeys.details(), id] as const,
}typescriptWith this hierarchical structure:
- Invalidate all user queries:
queryClient.invalidateQueries({ queryKey: userKeys.all }) - Invalidate lists while keeping individual user detail cached:
queryClient.invalidateQueries({ queryKey: userKeys.lists() }) - Subscribe to a specific record:
queryKey: userKeys.detail(userId)
11. When to Adopt and When to Pass#
Ideal Fit For TanStack Query#
- Data-heavy web apps (SaaS platforms, CRM dashboards, E-commerce storefronts).
- Applications with interdependent views sharing overlapping server entities.
- Single Page Applications (SPAs) built with React, Vite, or Next.js Client Components.
When TanStack Query is Unnecessary#
- Simple static websites fetching a single contact form endpoint.
- Architectures relying strictly on React Server Components (RSC) where data fetching and caching occur directly on the server level.
12. Summary#
TanStack Query is not merely an API fetching wrapper; it is an application-level server-state cache.
By embracing:
- The separation of Client State (Zustand/useState) vs. Server State (TanStack Query).
- Deterministic cache identity via
queryKey. - Clear boundaries between
staleTime(freshness) andgcTime(garbage collection). - Predictable workflows through Mutation ➔ Invalidation ➔ Refetch.
You eliminate asynchronous race conditions, optimize network efficiency, and build responsive applications your users will love.