Please thoroughly read the Important Defaults before reading this guide
This caching example illustrates the story and lifecycle of:
Query Instances with and without cache data
Background Refetching
Inactive Queries
Garbage Collection
Let's assume we are using the default gcTime of 5 minutes and the default staleTime of 0.
A new instance of injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })) initializes.
A second instance of injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })) initializes elsewhere.
Both instances of the injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })) query are destroyed and no longer in use.
Before the cache timeout has completed, another instance of injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })) mounts. The query immediately returns the available cached data while the fetchTodos function is being run in the background. When it completes successfully, it will populate the cache with fresh data.
The final instance of injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })) gets destroyed.
No more instances of injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })) appear within 5 minutes.
The cached data under the ['todos'] key is deleted and garbage collected.
For more advanced use-cases, see injectQuery.