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

prefetching.md

44 lines1.6 KB

1---
2id: prefetching
3title: Prefetching
4---
5​
6If you're lucky enough, you may know enough about what your users will do to be able to prefetch the data they need before it's needed! If this is the case, you can use the `prefetchQuery` method to prefetch the results of a query to be placed into the cache:
7​
8[//]: # 'Example'
9​
10```tsx
11const prefetchTodos = async () => {
12 // The results of this query will be cached like a normal query
13 await queryClient.prefetchQuery({
14 queryKey: ['todos'],
15 queryFn: fetchTodos,
16 })
18```
19​
20[//]: # 'Example'
21​
22- If data for this query is already in the cache and **not invalidated**, the data will not be fetched
23- If a `staleTime` is passed eg. `prefetchQuery({queryKey: ['todos'], queryFn: fn, staleTime: 5000 })` and the data is older than the specified staleTime, the query will be fetched
24- If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `cacheTime`.
25​
26## Manually Priming a Query
27​
28Alternatively, if you already have the data for your query synchronously available, you don't need to prefetch it. You can just use the [Query Client's `setQueryData` method](../reference/QueryClient#queryclientsetquerydata) to directly add or update a query's cached result by key.
29​
30[//]: # 'Example2'
31​
32```tsx
33queryClient.setQueryData(['todos'], todos)
34```
35​
36[//]: # 'Example2'
37​
38[//]: # 'Materials'
39​
40## Further reading
41​
42For a deep-dive on how to get data into your Query Cache before you fetch, have a look at [#17: Seeding the Query Cache](../community/tkdodos-blog#17-seeding-the-query-cache) from the Community Resources.
43​
44[//]: # 'Materials'