Capítulo 38 de 80

Chapter 38: Caching Examples

Core Idea

A worked walk-through of the default cache lifecycle (staleTime: 0, gcTime: 5min) for a single ['todos'] query, illustrating exactly when a mount is a hard load vs. an instant cache hit, and when a query is finally evicted.

Key Concepts

  • First mount, empty cache: no prior ['todos'] entry → hard loading state, real network request, result cached and immediately marked stale (staleTime: 0).
  • Second concurrent mount, same key: cached data is returned synchronously (no loading state for this instance), and this second observer also triggers its own background fetch — both observers share status/isFetching because they're both subscribed to the same underlying query, so both update together regardless of whether the two fetchTodos calls are literally the same function reference.
  • Both instances unmount: with zero active observers left, the query becomes "inactive" and a gcTime countdown (default 5 minutes) starts toward eviction.
  • A new mount before gcTime elapses: cached data renders instantly again (no hard loading state) while a background fetch refreshes it — the GC countdown is cancelled since there's an active observer again.
  • No mount within gcTime: the cache entry for ['todos'] is deleted; the next mount after that point starts the whole cycle over from a genuine hard loading state.

Reference Tables

EventLoading state?Network request?GC timer
1st mount, empty cacheHard loadingYes
2nd concurrent mount, same keyNone (cache hit)Yes (background)
All observers unmountStarts (gcTime)
New mount before gcTime expiresNone (cache hit)Yes (background)Cancelled
No mount within gcTimeEntry deleted

Key Takeaways

  1. "Hard loading state" only ever happens on a truly cold cache entry — any subsequent mount within gcTime, no matter how many prior instances unmounted, is a cache hit with a background refresh.
  2. Multiple simultaneous observers of the same key aren't independent — they share one underlying query, one fetch-in-flight, and one status.
  3. gcTime's countdown resets to "not scheduled" the instant a new observer mounts — it's not a rolling deadline from the query's creation, it's purely about "how long can this sit with zero observers."

Connects To

  • Important Defaults: the staleTime/gcTime defaults this walkthrough is built on.
  • Queries: the status/isFetching fields referenced throughout.