0Pricing
React Academy · Lesson

Caching, Stale Time & Background Refetching

Configure staleTime and gcTime to control when data is re-fetched from the server.

Caching, Stale Time & Background Refetching is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

In this lesson you will configure staleTime and gcTime to control how long React Query keeps data fresh and how long it retains cached data in memory.

Fresh vs Stale Data

React Query tracks whether cached data is 'fresh' or 'stale'. Fresh data is returned immediately without a network request. Stale data is returned immediately but a background refetch starts to update it.

staleTime

staleTime defines how long (milliseconds) data remains fresh. Default is 0 (immediately stale). Setting it to 60000 means data fetched within the last minute is returned without a background refetch.
useQuery({
  queryKey: ['users'],
  queryFn: fetchUsers,
  staleTime: 60_000, // fresh for 60 seconds
})

Setting staleTime for Static Data

For data that rarely changes (e.g. country list, config options), set a high staleTime. For live data (e.g. stock prices), keep the default 0 and enable polling.
// Effectively never stale — reload only on explicit invalidation
useQuery({ queryKey: ['countries'], queryFn: fetchCountries,
  staleTime: Infinity })

gcTime (Garbage Collection)

gcTime (formerly cacheTime) defines how long UNUSED cached data stays in memory before being garbage collected. Default is 5 minutes. Even after gcTime, React Query can immediately refetch if a new subscriber mounts.
useQuery({
  queryKey: ['products'],
  queryFn: fetchProducts,
  gcTime: 10 * 60 * 1000, // keep in memory for 10 minutes
})

staleTime vs gcTime

staleTime controls WHEN to refetch (data freshness). gcTime controls WHEN to discard cached data from memory. staleTime <= gcTime is the typical relationship.

Background Refetching Indicators

When React Query refetches in the background, `isFetching` is true even though `isLoading` is false (data is already cached). Use isFetching to show a subtle spinner.
const { data, isLoading, isFetching } = useQuery({ /* ... */ });

return (
  <>
    {isLoading ? <Spinner /> : <DataView data={data} />}
    {isFetching && !isLoading && <RefreshIndicator />}
  </>
);

refetchOnWindowFocus

By default, React Query refetches stale queries when the user switches back to the tab. Disable this for data that updates rarely.
useQuery({
  queryKey: ['settings'],
  queryFn: fetchSettings,
  refetchOnWindowFocus: false,
})

refetchInterval for Polling

Set `refetchInterval` to automatically poll a query on a timer. Useful for live data dashboards.
useQuery({
  queryKey: ['liveStats'],
  queryFn: fetchStats,
  refetchInterval: 5000, // every 5 seconds
})

Placeholder Data

Use `placeholderData` to show previous data while a refetch is in progress, preventing layout shifts. The keepPreviousData option makes this easy for pagination.
import { keepPreviousData } from '@tanstack/react-query';

useQuery({
  queryKey: ['posts', page],
  queryFn: () => fetchPage(page),
  placeholderData: keepPreviousData,
})

Quick Check

What does setting staleTime: Infinity on a query achieve?

Recap

staleTime controls freshness — how long before data triggers a background refetch. gcTime controls memory — how long unused data stays cached. isFetching signals background refetches. Use placeholderData for smooth pagination.

Up Next

Next lesson: **Mutations with useMutation** — you will post data to APIs and invalidate queries on success.

Frequently asked questions

Is the “Caching, Stale Time & Background Refetching” lesson free?

Yes — the full text of “Caching, Stale Time & Background Refetching” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Caching, Stale Time & Background Refetching”?

Configure staleTime and gcTime to control when data is re-fetched from the server. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Caching, Stale Time & Background Refetching” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Setting Up React Query & QueryClient
  2. Caching, Stale Time & Background Refetching
  3. Mutations with useMutation
  4. Infinite Scroll & Pagination with useInfiniteQuery
← Back to React Academy