blog.dopana

Back

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

In 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 for fetch() or axios. It functions as a Client-Side Server-State Cache, orchestrating data deduplication, automatic background synchronization, cache lifecycle management (staleTime vs. 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:

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

Remote InfrastructureReact ApplicationServer State (TanStack Query)Client State (Zustand / useState)Frontend Owns StateSnapshot Cached in RAMTheme: dark / lightModal open: true / falseActive Tab: 2User Profile RecordOrder History ListShopping Cart ItemsDatabase or REST Server

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:

App.tsx
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>
  )
}
tsx

Next, consume the query inside your component:

The 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: [ ... ]
text

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

3 Components Mount ConcurrentlyRemote API ServerRemote API ServerTanStack Query Cache LayerTanStack Query Cache LayeruseQueryuseQueryuseQuerySingle Network RequestResponse JSON PayloadDistribute to All ConsumersRenderRenderRenderHeader AvatarSidebar ProfileMain Dashboard ViewqueryKey: ['user', 123]Deduplication Engine (SinglePromise)GET /api/users/123

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.

OptionFormer NameOperational DefinitionDefault Value
staleTimestaleTimeHow long is retrieved data considered fresh before transitioning to stale?0 ms
gcTimecacheTimeHow 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 memory
text

[!TIP] Golden Rule: Setting staleTime: 60000 does 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):

queries/categories.ts
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
}
typescript

6. 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 = 0
text

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

POST api users200 SuccessinvalidateQueries1. User clicks Add User2. useMutation3. Server writes to DB4. onSuccess callback5. Mark users query as stale6. Automatic backgroundrefetch7. UI reflects latest state

Here is a standard production pattern:

8. 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:

9. 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:

1. Application Layer (React Memory)3. Network Infrastructure Layer3. Network Infrastructure Layer2. Browser Network Layer (HTTP Stack)2. Browser Network Layer (HTTP Stack)useQueryCache Miss or RevalidateCache MissForward304 or 200 OKJSON ObjectRe-render ComponentReact ComponentTanStack Query Cachefetch() / XMLHttpRequestHTTP Disk / Memory Cache(ETag, max-age)CDN Edge CacheBackend Server / Database
DimensionTanStack QueryHTTP Browser Cache
Storage LocationJavaScript Heap MemoryBrowser Disk / Network Cache
Component AwarenessFully aware of React lifecycle (mount, unmount, focus)Purely handles URLs, HTTP verbs, and headers
UI ReactivityTriggers reactive re-renders when data updatesCompletely decoupled from DOM rendering
Request DeduplicationShares single active promise across componentsMay fire parallel requests if triggered simultaneously
Mutations & RollbackFirst-class optimistic updates and targeted invalidationNone

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:

queries/userKeys.ts
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,
}
typescript

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

  1. The separation of Client State (Zustand/useState) vs. Server State (TanStack Query).
  2. Deterministic cache identity via queryKey.
  3. Clear boundaries between staleTime (freshness) and gcTime (garbage collection).
  4. Predictable workflows through Mutation ➔ Invalidation ➔ Refetch.

You eliminate asynchronous race conditions, optimize network efficiency, and build responsive applications your users will love.

References#