blog.dopana

Back

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/123
text

If 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.

Component AGET /api/users/123Component BGET /api/users/123

That creates redundant requests.

One solution is to build your own cache:

cache.ts
const cache = new Map()
ts

But 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:

terminal
npm install @tanstack/react-query
bash

The 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:

ThemeToggle.tsx
const [isOpen, setIsOpen] = useState(false)
tsx

Or:

ThemeToggle.tsx
const [theme, setTheme] = useState("dark")
tsx

This data belongs to the frontend.

Server State#

Data that comes from the backend.

For example:

user.json
{
  "id": 123,
  "name": "John",
  "email": "john@example.com"
}
json

The frontend does not really own this data.

The backend is the source of truth.

APIServer(source of truth)TanStack QueryCacheComponent AComponent B

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 State
text

For example:

ui-store.ts
{
  sidebarOpen: true,
  theme: "dark"
}
ts

fits Zustand/Redux.

While:

server-state.ts
{
  users: [...],
  posts: [...],
  products: [...],
  profile: {...}
}
ts

if 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:

UserProfile.tsx
const { data } = useQuery({
  queryKey: ["user", userId],
  queryFn: () => fetchUser(userId),
})
tsx

TanStack Query uses:

queryKey
ts

to identify which data is cached.

For example:

["user", 123]
text

and:

["user", 456]
text

are 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 queryKey as 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.

App.tsx
import {
  QueryClient,
  QueryClientProvider,
} from "@tanstack/react-query"

const queryClient = new QueryClient()

export function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <MyApp />
    </QueryClientProvider>
  )
}
tsx

Then use a query:

The noteworthy part is:

queryKey: ["user", userId]
ts

which is the identity of the cache.

[!NOTE] Since TanStack Query v5, the initial loading state is isPending (replacing v4’s isLoading), and cacheTime was renamed to gcTime. The examples in this post use the v5 API.

When a second component calls the same API#

Suppose component A renders:

<UserProfile userId={123} />
tsx

Then component B also uses:

<UserProfile userId={123} />
tsx

TanStack Query knows that:

["user", 123]
text

already exists in the Query Cache.

So component B sees the available data immediately instead of a blank loading screen.

Component Amounts firstQuery Cache['user', 123]Component Bmounts laterAPI Request(only when needed)

This is one of TanStack Query’s biggest strengths.

[!NOTE] By default staleTime is 0, 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 ─┘
text

If all three components mount almost simultaneously, you don’t want to send:

GET /api/user/123
GET /api/user/123
GET /api/user/123
text

TanStack Query shares/deduplicates requests based on the query key.

Conceptually:

Component AQuery Cache['user', 123]Component BComponent C1 single API Request

staleTime – how long is data considered fresh?#

This is a very important option.

For example:

UsersList.tsx
useQuery({
  queryKey: ["users"],
  queryFn: fetchUsers,
  staleTime: 60_000,
})
tsx

means the data is considered fresh for 60 seconds.

During that time, if another component uses:

["users"]
ts

TanStack 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 stale
text

staleTime is not cache deletion time#

This is a very common misunderstanding.

For example:

staleTime: 60_000
ts

does 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: staleTime is “how long data stays fresh”, NOT “how long the cache lives”. After staleTime expires, data is only marked stale — the next usage triggers a background refetch, but the cache is not deleted.

gcTime#

TanStack Query also has:

gcTime
ts

previously known as:

cacheTime
text

It concerns how long unused data is kept before being garbage collected.

For example:

UsersList.tsx
useQuery({
  queryKey: ["users"],
  queryFn: fetchUsers,
  staleTime: 60_000,
  gcTime: 5 * 60_000,
})
tsx

Simply put:

staleTime
    ↓
How long is data considered fresh?

gcTime
    ↓
How long is inactive cache kept?
text

These two concepts are different.

[!NOTE] Defaults: staleTime is 0 (stale immediately), gcTime is 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:

ProductsList.tsx
const productsQuery = useQuery({
  queryKey: ["products"],
  queryFn: fetchProducts,
  staleTime: 5 * 60 * 1000,
  gcTime: 30 * 60 * 1000,
})
tsx

Which means:

5 minutes
↓
data considered fresh

30 minutes
↓
inactive cache may be garbage collected
text

This 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 use staleTime: 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"
text

Frontend cache:

User name = "John"
text

Then the server changes:

Backend
  ↓
User name = "Mike"
text

The frontend cache may still contain:

John
text

So client-side caching always involves a trade-off:

Performance
    ↕
Freshness
text

To reduce API requests:

staleTime ↑
text

To keep data frequently updated:

staleTime ↓
text

Refetching data#

TanStack Query can refetch in many situations.

For example, when the user returns to the browser tab:

UsersList.tsx
useQuery({
  queryKey: ["users"],
  queryFn: fetchUsers,
  refetchOnWindowFocus: true,
})
tsx

Concept:

User leaves tabServer data changesUser returns to tabTanStack Query refetches

This makes the app feel always up to date without developers writing event listeners themselves.

[!NOTE] refetchOnWindowFocus defaults to true — 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 /users
text

After creating a user:

api.ts
await createUser(data)
ts

you can invalidate:

UsersList.tsx
queryClient.invalidateQueries({
  queryKey: ["users"],
})
ts

TanStack Query then knows the query:

["users"]
text

has become stale and can refetch.

Flow:

POST /userscreated successfullyinvalidate ['users']query becomes stalerefetchUI updates

Mutation#

TanStack Query also has useMutation().

CreateUser.tsx
const mutation = useMutation({
  mutationFn: createUser,
})
tsx

Usage:

CreateUser.tsx
mutation.mutate({
  name: "John",
})
tsx

Complete example:

UsersList.tsx
const queryClient = useQueryClient()

const mutation = useMutation({
  mutationFn: createUser,

  onSuccess: () => {
    queryClient.invalidateQueries({
      queryKey: ["users"],
    })
  },
})
tsx

This is a very common pattern:

MutationInvalidateRefetchUpdate UI

Optimistic Update#

A more advanced feature is the Optimistic Update.

For example, the user clicks:

❤️ Like
text

Instead of:

Click
 ↓
API request
 ↓
Server response
 ↓
Update UI
text

you can do:

Click
 ↓
Update UI immediately
 ↓
API request
 ↓
Success → keep it
Failure → rollback
text

Users will feel the app is faster.

For example:

User clicks Like10 → 11 instantlyPOST /likesuccess → keep iterror → rollback to 10

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 Cache
text

Page reload:

F5
 ↓
JavaScript memory lost
 ↓
Query cache lost
text

To persist the cache, TanStack Query can be combined with a persistence mechanism such as:

localStorage
IndexedDB
text

to 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 cache
text

For example:

React ComponentTanStack Query Cachefetch()Browser HTTP CacheNetworkBackend

TanStack Query understands:

queryKey
staleTime
invalidation
mutation
query state
ts

While HTTP cache relies on HTTP mechanisms such as:

Cache-Control
ETag
Last-Modified
Age
text

The two systems can work together.

Compared to hand-rolled cache#

Without TanStack Query:

cache.ts
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
}
ts

Looks 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?
text

At 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:

React AppClient StateZustand — UI stateServer StateTanStack Query — API cache

Zustand example:

ui-store.ts
{
  sidebarOpen: true,
  selectedTheme: "dark"
}
ts

TanStack Query:

server-state.ts
{
  users: [...],
  posts: [...],
  profile: {...}
}
ts

You 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
 └─SWR
text

Both 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 State
text

then 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 platform
text

especially when the application has many APIs.

For example:

/users
/users/:id
/courses
/courses/:id
/students
/students/:id
/reports
/notifications
text

Instead of each component managing:

fetch
loading
error
cache
refetch
text

let TanStack Query manage server state.

When don’t you necessarily need TanStack Query?#

If the application is extremely simple:

SimpleData.tsx
const [data, setData] = useState()

useEffect(() => {
  fetch("/api/data")
    .then(...)
}, [])
tsx

and 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.ts
text

For example:

queries/users.ts
// queries/users.ts

export const usersQuery = () => ({
  queryKey: ["users"],
  queryFn: fetchUsers,
})
ts

Component:

UserList.tsx
const { data, isPending } = useQuery(
  usersQuery()
)
tsx

This 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" }]
ts

Picture it as:

users
├─users/123
├─users/456
└─users?page=1&search=john
text

The more consistently query keys are designed, the easier:

invalidateQueries()
ts

and cache management become.

[!TIP] Design query keys hierarchically from general to specific: ["users"] → ["users", id] → ["users", { page, search }]. Then invalidateQueries({ queryKey: ["users"] }) invalidates the whole subtree — just like deleting a folder instead of each file.

A complete example#

The flow is now clear:

ComponentuseQuery()Query CacheAPI → ServerMutationPOST /usersinvalidate ['users']refetchQuery Cache → UI updated

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 update
text

instead 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:

UI stateZustand / useStateServer stateTanStack QueryHTTP cacheBrowser / CDNPersistent dataBackend / Database

That is also the perspective that helps avoid storing all API data in Redux/Zustand unnecessarily.

References#