|
| 1 | +--- |
| 2 | +id: caching |
| 3 | +title: Caching Examples |
| 4 | +--- |
| 5 | + |
| 6 | +> Please thoroughly read the [Important Defaults](../guides/important-defaults) before reading this guide |
| 7 | +
|
| 8 | +## Basic Example |
| 9 | + |
| 10 | +This 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 | + |
| 17 | +Let's assume we are using the default `gcTime` of **5 minutes** and the default `staleTime` of `0`. |
| 18 | + |
| 19 | +- A new instance of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos }))` initializes. |
| 20 | + - Since no other queries have been made with the `['todos']` query key, this query will show a hard loading state and make a network request to fetch the data. |
| 21 | + - When the network request has completed, the returned data will be cached under the `['todos']` key. |
| 22 | + - The date will be marked as stale after the configured `staleTime` (defaults to `0`, or immediately). |
| 23 | +- A second instance of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })` initializes elsewhere. |
| 24 | + - Since the cache already has data for the `['todos']` key from the first query, that data is immediately returned from the cache. |
| 25 | + - The new instance triggers a new network request using its query function. |
| 26 | + - Note that regardless of whether both `fetchTodos` query functions are identical or not, both queries' [`status`](../reference/injectQuery) are updated (including `isFetching`, `isPending`, and other related values) because they have the same query key. |
| 27 | + - When the request completes successfully, the cache's data under the `['todos']` key is updated with the new data, and both instances are updated with the new data. |
| 28 | +- Both instances of the `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })` query are destroyed and no longer in use. |
| 29 | + - Since there are no more active instances of this query, a garbage collection timeout is set using `gcTime` to delete and garbage collect the query (defaults to **5 minutes**). |
| 30 | +- Before the cache timeout has completed, another instance of `injectQuery(() => ({ queryKey: ['todos'], queyFn: 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. |
| 31 | +- The final instance of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })` gets destroyed. |
| 32 | +- No more instances of `injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodos })` appear within **5 minutes**. |
| 33 | + - The cached data under the `['todos']` key is deleted and garbage collected. |
0 commit comments