Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

caching.md

32 lines2.0 KB

1---
2id: caching
3title: Caching Examples
4---
5​
6> Please thoroughly read the [Important Defaults](./important-defaults) before reading this guide
7​
8## Basic Example
9​
10This caching example illustrates the story and lifecycle of:
11​
12- Query Instances with and without cache data
13- Background Refetching
14- Inactive Queries
15- Garbage Collection
16​
17Let's assume we are using the default `cacheTime` of **5 minutes** and the default `staleTime` of `0`.
18​
19- A new instance of `useQuery('todos', fetchTodos)` mounts.
20 - Since no other queries have been made with this query + variable combination, this query will show a hard loading state and make a network request to fetch the data.
21 - It will then cache the data using `'todos'` and `fetchTodos` as the unique identifiers for that cache.
22 - The hook will mark itself as stale after the configured `staleTime` (defaults to `0`, or immediately).
23- A second instance of `useQuery('todos', fetchTodos)` mounts elsewhere.
24 - Because this exact data exists in the cache from the first instance of this query, that data is immediately returned from the cache.
25- A background refetch is triggered for both queries (but only one request), since a new instance appeared on screen.
26 - Both instances are updated with the new data if the fetch is successful
27- Both instances of the `useQuery('todos', fetchTodos)` query are unmounted and no longer in use.
28 - Since there are no more active instances of this query, a cache timeout is set using `cacheTime` to delete and garbage collect the query (defaults to **5 minutes**).
29- Before the cache timeout has completed another instance of `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.
30- The final instance of `useQuery('todos', fetchTodos)` unmounts.
31- No more instances of `useQuery('todos', fetchTodos)` appear within **5 minutes**.
32 - This query and its data are deleted and garbage collected.