| | |

Vue Query 05 ⚡ Caching Lifecycle (staleTime vs gcTime) — Mastering freshness, garbage collection, and background refetching

⏱️ Estimated read: 11 min | |

Caching is the most powerful and often the most misunderstood aspect of Vue Query. In a standard data-fetching setup, data is either “present” or “absent.” Vue Query introduces a more nuanced state machine where data can be “fresh,” “stale,” or “inactive.” This lifecycle is governed by two primary settings: staleTime and gcTime (formerly cacheTime). Mastering the interplay between these two durations allows you to build applications that feel instantaneous to the user while maintaining high data integrity and efficient memory usage.

staleTime defines the duration for which data is considered “fresh.” During this window, Vue Query will reuse the cached data without making any network requests. Once this time expires, the data becomes “stale,” meaning it is still usable, but the library will trigger a background refetch the next time a component mounts or a revalidation trigger (like window focus) occurs. This “Stale-While-Revalidate” pattern is the secret to a fast UI: users see the old data immediately while the app quietly updates to the latest version in the background.

gcTime, on the other hand, is the “Garbage Collection” timer. It dictates how long data remains in the cache after all components using that specific query have unmounted. While staleTime is about data accuracy, gcTime is about memory management. Together with automatic revalidation triggers like refetchOnWindowFocus and refetchOnReconnect, these settings form a robust synchronization engine that keeps your client-side data in harmony with the server without overwhelming your API with redundant requests.

This chapter breaks down the query lifecycle from the first fetch to the final deletion from memory. We will examine the specific transitions between cache states, the impact of global vs. local configurations, and how to use revalidation triggers to ensure your application remains “live” even when users step away from their browsers.

Key point: staleTime determines when data should be updated in the background, while gcTime determines when unused data should be completely removed from memory; data can be both stale and cached simultaneously.


Why exists

The Redundant Request problem.
Without a “freshness” window, every time a user navigates between a product list and a product detail page, the list would refetch. This creates unnecessary server load and a flickering UI. staleTime exists to define a “grace period” where the client can confidently reuse what it already knows, saving bandwidth and improving perceived speed.

The Memory Leak problem.
As users navigate through a large application, they might view hundreds of different resources (User profiles, blog posts, etc.). If every API response was kept in memory forever, the browser would eventually slow down or crash. gcTime exists to automatically prune the cache, removing data that hasn’t been looked at for a significant amount of time.

The “User Left the Tab” problem.
A user might open your dashboard, get a phone call, and return to their computer an hour later. The data on their screen is now dangerously out of date. refetchOnWindowFocus exists to detect when the user returns to the application and automatically refresh any “stale” data, ensuring they always see the most current information without manual action.

The Connectivity Fluctuation problem.
In a mobile environment, network connections drop and recover constantly. If a user is filling out a form and their Wi-Fi reconnects, the app should verify that the supporting data is still correct. refetchOnReconnect exists to handle these environmental changes, providing a resilient synchronization layer that adapts to the user’s connection status.

The “Flash of Loading” problem.
Traditional apps show a spinner every time data is fetched. staleTime and the “Stale-While-Revalidate” approach exist to eliminate the spinner for repeated visits. By showing “good enough” (stale) data immediately, the app feels much faster, and the user only sees an update when the background fetch completes.

The “Static Data” problem.
Some data, like a list of countries or a user’s own birthdate, almost never changes. Fetching this data every few minutes is wasteful. The caching lifecycle settings allow developers to set staleTime: Infinity, effectively telling Vue Query that once this data is fetched once, it should never be refetched unless the cache is manually invalidated.


a. staleTime: Defining Data Freshness

In Vue Query, data is either Fresh or Stale.

  • Fresh: The data is reliable. Components using this query will not trigger a refetch.
  • Stale: The data might be old. Components using this query will still show the data but will also trigger a background refetch to get the latest version.

The default staleTime is 0. This means that by default, all data becomes stale immediately after it is fetched. If you navigate away and back, it will refetch.

// Local override for a specific query
const { data } = useQuery({
  queryKey: ['settings'],
  queryFn: fetchSettings,
  // Data is fresh for 5 minutes
  staleTime: 1000 * 60 * 5, 
})

When staleTime is set, Vue Query checks the timestamp of the cached data. If the elapsed time is less than the staleTime, the data is returned from the cache, and isFetching remains false. If the time has passed, the data is still returned from the cache, but isFetching becomes true as the background request starts.


b. gcTime: Managing Garbage Collection

gcTime (Garbage Collection Time) was previously known as cacheTime in older versions of the library. It measures the time from when a query becomes “inactive” (meaning no more components are mounting it) to when it is deleted from the QueryClient cache.

The default gcTime is 5 minutes.

const { data } = useQuery({
  queryKey: ['temp-data'],
  queryFn: fetchTemp,
  staleTime: 0,
  // If the user leaves the page, delete this from memory after 30 seconds
  gcTime: 1000 * 30, 
})

The logic flow is as follows:

  1. Component unmounts.
  2. Query becomes “Inactive.”
  3. gcTime starts counting down.
  4. If a component mounts the query before the timer ends, the timer is canceled and the query becomes “Active” again.
  5. If the timer reaches zero, the data is deleted.

It is important that gcTime is usually longer than staleTime. If you delete data from the cache before it even becomes stale, you lose the benefit of the “Stale-While-Revalidate” pattern because there will be no data to show while the refetch happens.


c. Revalidation Triggers: Focus and Reconnect

Vue Query doesn’t just refetch when components mount; it also listens to global window events to ensure data stays fresh. These behaviors only trigger if the data is already marked as stale.

  1. refetchOnWindowFocus: (Default: true) Triggers a background refetch when the browser tab gains focus. This is excellent for keeping data current when users switch between apps.
  2. refetchOnReconnect: (Default: true) Triggers a background refetch when the browser detects that the internet connection has returned after being offline.
  3. refetchOnMount: (Default: true) Triggers a background refetch whenever a new component instance using the query is mounted.
const { data } = useQuery({
  queryKey: ['stock-prices'],
  queryFn: fetchPrices,
  staleTime: 1000 * 10, // 10 seconds
  // Disable automatic window focus refetch for this specific query
  refetchOnWindowFocus: false,
})

You can also set these triggers to 'always', which means they will refetch even if the data is technically still “fresh” (within its staleTime). This is rarely needed but can be useful for highly volatile data like live sports scores or stock tickers.


Complete Example Session

// ============================================
// PART 1: THE GLOBAL DEFAULTS
// ============================================
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60, // 1 minute freshness
      gcTime: 1000 * 60 * 10, // 10 minute memory life
    },
  },
})

// ============================================
// PART 2: THE IMMUTABLE DATA PATTERN
// ============================================
// Data that never changes (e.g., Country List)
const { data: countries } = useQuery({
  queryKey: ['countries'],
  queryFn: fetchCountries,
  staleTime: Infinity, // Never stale
  gcTime: 1000 * 60 * 60, // Keep in memory for an hour
})

// ============================================
// PART 3: THE VOLATILE DATA PATTERN
// ============================================
// Data that changes constantly (e.g., Notifications)
const { data: alerts } = useQuery({
  queryKey: ['alerts'],
  queryFn: fetchAlerts,
  staleTime: 0, // Always stale
  refetchOnWindowFocus: true // Update every time user returns
})

// ============================================
// PART 4: THE INACTIVE CYCLE
// ============================================
// 1. User is on /profile (ProfileQuery is ACTIVE)
// 2. User moves to /settings (ProfileQuery becomes INACTIVE)
// 3. gcTime for ProfileQuery starts...
// 4. User returns to /profile after 2 mins (ProfileQuery becomes ACTIVE)
// 5. gcTime is canceled.

// ============================================
// PART 5: REFETCH ON FOCUS BEHAVIOR
// ============================================
// User leaves tab for 2 minutes.
// staleTime (1 min) has passed -> Data is STALE.
// User returns to tab -> refetchOnWindowFocus triggers background fetch.

// ============================================
// PART 6: MANUAL INVALIDATION
// ============================================
// This forces data to be stale immediately regardless of staleTime
// queryClient.invalidateQueries({ queryKey: ['user'] })

// ============================================
// PART 7: FETCHING VS PENDING
// ============================================
// When refetch happens:
// data.value = [old data]
// isFetching.value = true
// isPending.value = false (because data exists in cache)

// ============================================
// PART 8: STALE WHILE REVALIDATE UI
// ============================================
/*
<template>
  <div :class="{ 'opacity-50': isFetching }">
    {{ data }}
  </div>
</template>
*/

// ============================================
// PART 9: THE ZERO CACHE CONFIG
// ============================================
// Equivalent to traditional fetching (no caching)
// staleTime: 0, gcTime: 0

// ============================================
// PART 10: DEBUGGING WITH DEVTOOLS
// ============================================
// Watch the "Fresh", "Stale", and "Inactive" labels in the 
// Vue Query Devtools panel to see these timers in action.

The session above illustrates the logical flow of data through various states and how settings like Infinity or 0 can be used to create specific architectural patterns.


Quick Reference

Cache States

StateStatusMeaning
FreshstaleTime activeData is valid; no network calls on mount.
StalestaleTime expiredData is old; background refetch on mount/focus.
FetchingNetwork activeRequest is currently in-flight.
InactiveNo observersNo active components using the query; gcTime counting.
DeletedgcTime expiredData removed from memory.

Comparison: staleTime vs. gcTime

FeaturestaleTimegcTime
PurposeData AccuracyMemory Management
Default05 minutes
TriggerClock starts on successClock starts on unmount
ResultTriggers refetchDeletes from cache

Revalidation Defaults

OptionDefaultDescription
refetchOnMounttrueRefetch when component mounts (if stale).
refetchOnWindowFocustrueRefetch when browser tab is focused (if stale).
refetchOnReconnecttrueRefetch when network returns (if stale).

Best Practices

✅ Do This:

// Set a global staleTime (e.g. 30s) to avoid excessive fetching
queries: { staleTime: 30000 }                                  // ✅

// Ensure gcTime is always >= staleTime
staleTime: 60000, gcTime: 300000                               // ✅

// Use staleTime: Infinity for data that truly never changes
queryKey: ['config'], staleTime: Infinity                      // ✅

// Keep refetchOnWindowFocus enabled for dynamic, multi-user apps
// (It keeps the client in sync with the server automatically)   // ✅

❌ Don’t Do This:

// Don't set gcTime: 0 unless you want to disable caching entirely
// (This forces a loading spinner on every mount)               // ❌

// Don't set a very long staleTime for highly volatile data
// (User might see very old data for too long)                 // ❌

// Don't assume gcTime deletes data while a component is using it
// (Only inactive queries are garbage collected)               // ❌

// Don't set staleTime to a huge number just to "fix" spinners
// (Use initialData or placeholderData instead)                // ❌

Common Pitfalls

PitfallWhy It HappensFix
Constant RefetchingDefault staleTime is 0Increase global or local staleTime
No Spinner on Second VisitData is still in cache (stale)Check isFetching instead of isPending
Memory usage too highgcTime is set too long for large datasetsReduce gcTime to 1 or 2 minutes
Tab Focus hammers APIrefetchOnWindowFocus with staleTime: 0Increase staleTime or disable focus refetch
Initial Load is slowNo caching being utilizedCheck that queryKey is consistent across pages
Data deleted too soongcTime was shorter than the user’s nav timeIncrease gcTime (default 5m is usually fine)

Real-World Examples

1. Real-time Dashboard (Aggressive)

staleTime: 0, refetchInterval: 5000

2. E-commerce Product List

staleTime: 1000 * 60, gcTime: 1000 * 60 * 10

3. User Profile (Private)

staleTime: 30000, refetchOnWindowFocus: true

4. App Configurations (Static)

staleTime: Infinity, gcTime: Infinity

5. Search Results (Short-lived)

staleTime: 5000, gcTime: 1000 * 60

6. Form Options (Cached for Session)

staleTime: 1000 * 60 * 30

7. Blog Posts (Long staletime)

staleTime: 1000 * 60 * 15

8. Stock Ticker (Always Revalidate)

refetchOnWindowFocus: 'always'

9. Temporary Data Cleanup

gcTime: 0 // Delete immediately after unmount

10. Background Sync only

refetchOnMount: false, refetchOnWindowFocus: true

Visual

Cache Status Transitions

    FETCH SUCCESS
          │
          ▼
    [ FRESH ] ──(staleTime expires)──► [ STALE ]
          │                               │
          │                        (User Focus / Mount)
          │                               │
          │                        [ BACKGROUND FETCH ]
          │                               │
          └──────────────◄────────────────┘
                         │
                  (All observers leave)
                         │
                         ▼
                    [ INACTIVE ] ──(gcTime expires)──► [ DELETED ]

Stale-While-Revalidate Flow

USER ACTION: Navigate to /posts
      │
      ▼
Check Cache: Key ['posts'] found but STALE
      │
      ▼
ACTION 1: Immediately show [Cached Data] (UI is populated)
      │
      ▼
ACTION 2: Start Network Fetch (isFetching: true)
      │
      ▼
ACTION 3: Data arrives -> Update Cache -> UI updates with fresh data

Memory Management (gcTime)

┌──────────────────────────────────────────────────────────┐
│  ACTIVE (Component A uses Key X)                         │
├──────────────────────────────────────────────────────────┤
│  UNMOUNT (Component A leaves)                            │
│  State: INACTIVE                                         │
│  Timer: gcTime (5:00... 4:59...)                         │
├──────────────────────────────────────────────────────────┤
│  REMOUNT (Component A returns at 2:00)                   │
│  State: ACTIVE (Timer Canceled)                          │
└──────────────────────────────────────────────────────────┘

Summary

ItemValue
Freshness WindowstaleTime
Memory WindowgcTime (formerly cacheTime)
Default staleTime0 (Always stale)
Default gcTime5 minutes
Active StateAt least one component is using the query
Inactive StateNo components are using the query
Background RefetchHappens only if data is stale
Hard RefetchHappens if data is deleted or missing

Key takeaways:

  • staleTime is about speed. It controls how long you can reuse data without checking the server. Setting this higher than 0 is the key to removing redundant spinners .
  • gcTime is about memory. It controls how long unused data “lingers” in the background before being purged. It should almost always be longer than staleTime .
  • Stale data is still “Good” data. Vue Query will show stale data to the user immediately while updating it, preventing the “flash of empty state” that plagues traditional apps .
  • Window focus keeps the app alive. The default refetchOnWindowFocus: true ensures that when a user returns to your app, they are automatically seeing the most recent data .
  • Garbage collection only affects inactive queries. If a component is currently showing the data, the gcTime timer will never start, and the data will never be deleted .
  • Infinity is a valid setting. For data that is truly static (like application version or help text), staleTime: Infinity ensures only one network request is made per session .

Remember: staleTime manages the relationship between the client and the server (freshness), while gcTime manages the relationship between the client and the browser’s memory (existence). Configure them together to balance a lightning-fast UI with responsible resource usage.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!