React Query caching is automatic out of the box. It uses a stale-while-revalidate
in-memory caching strategy (popularized by HTTP RFC 5861) and a very robust query deduping strategy to always ensure a query's data is always readily available, only cached when it's needed, even if that query is used multiple times across your application and updated in the background when possible.
At a glance:
staleTime
option at both the global and query-level.cacheTime
option at both the global and query-level.cacheTime
specified (defaults to 5 minutes), the query is deleted and garbage collected.Let's assume we are using the default cacheTime
of 5 minutes and the default staleTime
of 0
.
useQuery('todos', fetchTodos)
mounts.'todos'
and fetchTodos
as the unique identifiers for that cache.staleTime
option as a delay (defaults to 0
, or immediately).useQuery('todos', fetchTodos)
mounts elsewhere.useQuery('todos', fetchTodos)
query are unmounted and no longer in use.cacheTime
to delete and garbage collect the query (defaults to 5 minutes).useQuery('todos', fetchTodos)
mounts. The query immediately returns the available cached value while the fetchTodos
function is being run in the background to populate the query with a fresh value.useQuery('todos', fetchTodos)
unmounts.useQuery('todos', fetchTodos)
appear within 5 minutes.The latest TanStack news, articles, and resources, sent to your inbox.