Client-side Cache in React with TanStack Query
TanStack Query as a client-side server-state cache: cache API data, deduplicate requests, auto refetch, manage loading/error.
Focusing on a simple understanding and practical application of TanStack Query in React — especially client-side caching.
TL;DR: @tanstack/react-query is not just an API-calling library. It can act as a client-side server-state cache, caching API data, avoiding duplicate requests, auto-refetching when needed, and conveniently managing loading/error states.
The Problem: Redundant API Requests#
When building a React application, we often run into a common problem:
The API already returned the data — do we need to call the API again next time?
For example, a page has this API:
GET /api/users/123textIf component A calls this API, and then component B also needs user 123’s info, the traditional approach may cause both components to call the API.
That creates redundant requests.
One solution is to build your own cache:
const cache = new Map()tsBut as the application grows, managing the cache yourself quickly becomes complicated.
This is where TanStack Query becomes useful.
What is TanStack Query?#
TanStack Query, formerly known as React Query, is a library for managing server state in the frontend.
The package for React is:
npm install @tanstack/react-querybashThe key point is:
TanStack Query is not simply a
fetch()API library.
It provides a system for:
- fetching data
- caching data
- request deduplication
- refetching data
- retrying requests
- managing loading/error
- invalidating cache
- optimistic updates
- pagination
- infinite queries
- background refetch
Server State vs Client State#
This is the most important concept for understanding TanStack Query.
Client State#
State that belongs to the UI/application.
For example:
const [isOpen, setIsOpen] = useState(false)tsxOr:
const [theme, setTheme] = useState("dark")tsxThis data belongs to the frontend.
Server State#
Data that comes from the backend.
For example:
{
"id": 123,
"name": "John",
"email": "john@example.com"
}jsonThe frontend does not really own this data.
The backend is the source of truth.
TanStack Query is designed primarily to solve this kind of state.
[!NOTE] ELI5: Client State is like the light switch in your house — you fully control it. Server State is like the weather outside — you can only “look” at it through a window (the API), you don’t own it, and it can change at any time.
Don’t confuse TanStack Query with Redux#
A simple way to think about it:
Redux/Zustand
↓
Client State
TanStack Query
↓
Server StatetextFor example:
{
sidebarOpen: true,
theme: "dark"
}tsfits Zustand/Redux.
While:
{
users: [...],
posts: [...],
products: [...],
profile: {...}
}tsif the data comes from an API, TanStack Query is usually a better fit.
Of course, both kinds of state can coexist in one application.
How does the cache work?#
For example:
const { data } = useQuery({
queryKey: ["user", userId],
queryFn: () => fetchUser(userId),
})tsxTanStack Query uses:
queryKeytsto identify which data is cached.
For example:
["user", 123]textand:
["user", 456]textare two different cache entries.
You can picture it like this:
Query Cache
"user", 123
↓
{ id: 123, name: "John" }
"user", 456
↓
{ id: 456, name: "Alice" }
"posts", 123
↓
[ ... ]text[!TIP] Think of
queryKeyas a locker number at the supermarket: each key opens exactly one compartment of data. Different keys → different compartments, never mixed up.
Basic example#
First, create a QueryClient.
import {
QueryClient,
QueryClientProvider,
} from "@tanstack/react-query"
const queryClient = new QueryClient()
export function App() {
return (
<QueryClientProvider client={queryClient}>
<MyApp />
</QueryClientProvider>
)
}tsxThen use a query:
import { useQuery } from "@tanstack/react-query"
function UserProfile({ userId }: { userId: number }) {
const { data, isPending, error } = useQuery({
queryKey: ["user", userId],
queryFn: () => fetch(`/api/users/${userId}`).then(res => res.json()),
})
if (isPending) {
return <div>Loading...</div>
}
if (error) {
return <div>Error</div>
}
return <div>{data.name}</div>
}tsxThe noteworthy part is:
queryKey: ["user", userId]tswhich is the identity of the cache.
[!NOTE] Since TanStack Query v5, the initial loading state is
isPending(replacing v4’sisLoading), andcacheTimewas renamed togcTime. The examples in this post use the v5 API.
When a second component calls the same API#
Suppose component A renders:
<UserProfile userId={123} />tsxThen component B also uses:
<UserProfile userId={123} />tsxTanStack Query knows that:
["user", 123]textalready exists in the Query Cache.
So component B sees the available data immediately instead of a blank loading screen.
This is one of TanStack Query’s biggest strengths.
[!NOTE] By default
staleTimeis0, meaning cached data is considered stale immediately. Component B still sees the old data instantly (no loading), while TanStack Query refetches in the background — this pattern is called stale-while-revalidate.
Request Deduplication#
A very common situation:
Component A ─┐
│
Component B ─┼──→ GET /api/user/123
│
Component C ─┘textIf all three components mount almost simultaneously, you don’t want to send:
GET /api/user/123
GET /api/user/123
GET /api/user/123textTanStack Query shares/deduplicates requests based on the query key.
Conceptually:
staleTime – how long is data considered fresh?#
This is a very important option.
For example:
useQuery({
queryKey: ["users"],
queryFn: fetchUsers,
staleTime: 60_000,
})tsxmeans the data is considered fresh for 60 seconds.
During that time, if another component uses:
["users"]tsTanStack Query can use the current cache instead of refetching immediately.
For example:
00s API request
↓
cache
10s component B
↓
use cache
30s component C
↓
use cache
60s cache becomes staletextstaleTime is not cache deletion time#
This is a very common misunderstanding.
For example:
staleTime: 60_000tsdoes not mean:
After 60 seconds the cache is deleted.
It only means:
After 60 seconds, the data is considered stale.
The data can still remain in the cache.
[!WARNING] The most common misunderstanding when learning TanStack Query:
staleTimeis “how long data stays fresh”, NOT “how long the cache lives”. AfterstaleTimeexpires, data is only marked stale — the next usage triggers a background refetch, but the cache is not deleted.
gcTime#
TanStack Query also has:
gcTimetspreviously known as:
cacheTimetextIt concerns how long unused data is kept before being garbage collected.
For example:
useQuery({
queryKey: ["users"],
queryFn: fetchUsers,
staleTime: 60_000,
gcTime: 5 * 60_000,
})tsxSimply put:
staleTime
↓
How long is data considered fresh?
gcTime
↓
How long is inactive cache kept?textThese two concepts are different.
[!NOTE] Defaults:
staleTimeis0(stale immediately),gcTimeis 5 minutes (inactive cache kept 5 minutes after the last component unmounts). These two numbers explain almost every “strange” behavior newcomers run into.
A practical configuration#
Example product API:
const productsQuery = useQuery({
queryKey: ["products"],
queryFn: fetchProducts,
staleTime: 5 * 60 * 1000,
gcTime: 30 * 60 * 1000,
})tsxWhich means:
5 minutes
↓
data considered fresh
30 minutes
↓
inactive cache may be garbage collectedtextThis is especially useful for rarely-changing data.
For example:
- country list
- categories
- school list
- configuration
- product catalog
- master data
[!TIP] Rule of thumb: the less frequently data changes, the longer the
staleTime. A country list can usestaleTime: Infinity; a realtime price board needs a few seconds or a refetch interval.
Cache does not mean data is always fresh#
This is a very important point.
Suppose:
Backend
↓
User name = "John"textFrontend cache:
User name = "John"textThen the server changes:
Backend
↓
User name = "Mike"textThe frontend cache may still contain:
JohntextSo client-side caching always involves a trade-off:
Performance
↕
FreshnesstextTo reduce API requests:
staleTime ↑textTo keep data frequently updated:
staleTime ↓textRefetching data#
TanStack Query can refetch in many situations.
For example, when the user returns to the browser tab:
useQuery({
queryKey: ["users"],
queryFn: fetchUsers,
refetchOnWindowFocus: true,
})tsxConcept:
This makes the app feel always up to date without developers writing event listeners themselves.
[!NOTE]
refetchOnWindowFocusdefaults totrue— one of those “important defaults” that surprise people: switching tabs makes the app call the API by itself. If you see “mystery” requests in DevTools, this is likely the culprit.
Invalidating Cache#
An extremely useful feature when doing CRUD.
For example:
GET /users
POST /userstextAfter creating a user:
await createUser(data)tsyou can invalidate:
queryClient.invalidateQueries({
queryKey: ["users"],
})tsTanStack Query then knows the query:
["users"]texthas become stale and can refetch.
Flow:
Mutation#
TanStack Query also has useMutation().
const mutation = useMutation({
mutationFn: createUser,
})tsxUsage:
mutation.mutate({
name: "John",
})tsxComplete example:
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: createUser,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["users"],
})
},
})tsxThis is a very common pattern:
Optimistic Update#
A more advanced feature is the Optimistic Update.
For example, the user clicks:
❤️ LiketextInstead of:
Click
↓
API request
↓
Server response
↓
Update UItextyou can do:
Click
↓
Update UI immediately
↓
API request
↓
Success → keep it
Failure → rollbacktextUsers will feel the app is faster.
For example:
This is one of the use cases where hand-rolled cache/state management gets complicated fast.
Does TanStack Query store cache in LocalStorage?#
By default:
No.
The query cache lives mostly in memory.
For example:
Browser
└─JavaScript Memory
└─TanStack Query CachetextPage reload:
F5
↓
JavaScript memory lost
↓
Query cache losttextTo persist the cache, TanStack Query can be combined with a persistence mechanism such as:
localStorage
IndexedDBtextto create a persistent cache.
This suits apps that want to keep some server state after reload/offline.
Is TanStack Query an HTTP Cache?#
These two should not be confused.
There are at least two different cache layers:
Browser / HTTP Cache
↓
HTTP response caching
TanStack Query
↓
Application-level server-state cachetextFor example:
TanStack Query understands:
queryKey
staleTime
invalidation
mutation
query statetsWhile HTTP cache relies on HTTP mechanisms such as:
Cache-Control
ETag
Last-Modified
AgetextThe two systems can work together.
Compared to hand-rolled cache#
Without TanStack Query:
const cache = new Map()
async function getUser(id: number) {
if (cache.has(id)) {
return cache.get(id)
}
const data = await fetch(`/api/users/${id}`)
.then(res => res.json())
cache.set(id, data)
return data
}tsLooks simple at first.
But then you must solve:
❓ How long to cache?
❓ When does cache go stale?
❓ When to refetch?
❓ Retry?
❓ Loading?
❓ Error?
❓ Deduplicate?
❓ Mutation?
❓ Invalidate?
❓ Pagination?
❓ Infinite scroll?
❓ Optimistic update?
❓ Garbage collection?
❓ Concurrent request?
❓ Offline?textAt that point the simple Map() has turned into a complete caching system.
TanStack Query solves most of those problems.
TanStack Query vs Zustand#
A typical React architecture can use both:
Zustand example:
{
sidebarOpen: true,
selectedTheme: "dark"
}tsTanStack Query:
{
users: [...],
posts: [...],
profile: {...}
}tsYou don’t have to choose one or the other.
TanStack Query vs SWR#
Another popular choice in React/Next.js is SWR.
The concepts of both are quite similar:
React
├─TanStack Query
└─SWRtextBoth solve:
- fetching
- caching
- revalidation
- server state
TanStack Query usually offers a broader query/mutation system and server-state management capabilities, while SWR has a fairly minimal API.
So if the application has a lot of:
CRUD
Mutation
Pagination
Infinite Query
Optimistic Update
Cache Invalidation
Complex Server Statetextthen TanStack Query is worth considering.
When should you use TanStack Query?#
TanStack Query is especially suitable for:
Dashboard
Admin panel
E-commerce
CRM
SaaS
Social network
Healthcare application
Education platformtextespecially when the application has many APIs.
For example:
/users
/users/:id
/courses
/courses/:id
/students
/students/:id
/reports
/notificationstextInstead of each component managing:
fetch
loading
error
cache
refetchtextlet TanStack Query manage server state.
When don’t you necessarily need TanStack Query?#
If the application is extremely simple:
const [data, setData] = useState()
useEffect(() => {
fetch("/api/data")
.then(...)
}, [])tsxand has only a few API requests, adding a library may not bring much benefit.
Similarly, if the framework already provides a powerful server-data fetching/caching mechanism and the application mostly uses server components, consider the overall architecture before adding a client-side query library.
A practical architecture#
For a large React SPA, you can organize:
src/
├─api/
│ ├─users.ts
│ ├─courses.ts
│ └─reports.ts
├─queries/
│ ├─users.ts
│ ├─courses.ts
│ └─reports.ts
├─components/
│ ├─UserList.tsx
│ └─CourseList.tsx
└─query-client.tstextFor example:
// queries/users.ts
export const usersQuery = () => ({
queryKey: ["users"],
queryFn: fetchUsers,
})tsComponent:
const { data, isPending } = useQuery(
usersQuery()
)tsxThis keeps API logic from mixing too much with UI.
An important pattern: Query Key#
When using TanStack Query, design structured query keys.
For example:
["users"]ts["users", userId]ts["users", { page: 1, search: "john" }]tsPicture it as:
users
├─users/123
├─users/456
└─users?page=1&search=johntextThe more consistently query keys are designed, the easier:
invalidateQueries()tsand cache management become.
[!TIP] Design query keys hierarchically from general to specific:
["users"]→["users", id]→["users", { page, search }]. TheninvalidateQueries({ queryKey: ["users"] })invalidates the whole subtree — just like deleting a folder instead of each file.
A complete example#
function UserList() {
const queryClient = useQueryClient()
const usersQuery = useQuery({
queryKey: ["users"],
queryFn: fetchUsers,
staleTime: 60_000,
})
const createMutation = useMutation({
mutationFn: createUser,
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["users"],
})
},
})
if (usersQuery.isPending) {
return <div>Loading...</div>
}
if (usersQuery.isError) {
return <div>Something went wrong</div>
}
return (
<>
{usersQuery.data.map(user => (
<div key={user.id}>
{user.name}
</div>
))}
<button
onClick={() =>
createMutation.mutate({
name: "John",
})
}
>
Add user
</button>
</>
)
}tsxThe flow is now clear:
Conclusion#
If your goal is client-side caching for API data in React, then @tanstack/react-query is well worth considering.
The most important thing to remember is not:
“TanStack Query is an API fetch library.”
But rather:
TanStack Query is a server-state management and client-side caching system.
It is especially useful when the application starts having many APIs and problems like:
API request duplication
+
Caching
+
Stale data
+
Refetch
+
Mutation
+
Cache invalidation
+
Optimistic updatetextinstead of building everything yourself with useEffect + useState + Map, you can let TanStack Query handle the server-state part.
A modern React architecture can be simplified to:
That is also the perspective that helps avoid storing all API data in Redux/Zustand unnecessarily.