Course contentsShow
← React
Lesson 1782 of 2,39642. Data Fetching LibrariesFree lesson

The staleTime Configuration

Controlling how long data is considered fresh before it becomes stale and eligible for refetching.

The staleTime Configuration

You'll learn how to precisely control how long fetched data stays fresh before TanStack Query considers it stale and ready for background refetching.

What Is staleTime?

The staleTime configuration is a duration (in milliseconds) that tells TanStack Query how long to consider data fresh after it's fetched. While data is fresh, TanStack Query won't refetch it—even if you remount a component or switch browser tabs. Once that time expires, the data becomes stale, and Query will refetch it the next time conditions trigger a refetch (like focus or mount).

Think of it like milk in your fridge: staleTime is the "best by" date. Before that date, you trust it's good. After that, you check if it needs replacing.

Setting staleTime

useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos,
  staleTime: 5 * 60 * 1000  // Fresh for 5 minutes
});

With staleTime: 5 * 60 * 1000, data remains fresh for 5 minutes. During those 5 minutes, remounting components or refocusing the window won't trigger refetches.

Common Values

  • staleTime: 0 (default) — Data is stale immediately, refetch on every opportunity
  • staleTime: 1000 * 60 — Fresh for 1 minute
  • staleTime: Infinity — Data never goes stale, never refetches automatically

When to Increase staleTime

Use longer staleTime for:

  • Rarely changing data (site configuration, user preferences)
  • Expensive API calls you want to minimize
  • Static content that updates infrequently

Use shorter staleTime (or default 0) for:

  • Real-time data (notifications, live scores)
  • User-generated content that changes frequently

Key Takeaway: staleTime controls the freshness window—how long TanStack Query trusts cached data before marking it stale and eligible for background refetching.