Open History to see the last commit
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[//]: # 'ExamplePrefetching'
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 })
17}
18```
19β
20[//]: # 'ExamplePrefetching'
21β
22- If **fresh** data for this query is already in the cache, 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 `gcTime`.
25β
26## Prefetching Infinite Queries
27β
28Infinite Queries can be prefetched like regular Queries. Per default, only the first page of the Query will be prefetched and will be stored under the given QueryKey. If you want to prefetch more than one page, you can use the `pages` option, in which case you also have to provide a `getNextPageParam` function:
29β
30[//]: # 'ExampleInfiniteQuery'
31```tsx
32const prefetchTodos = async () => {
33 // The results of this query will be cached like a normal query
34 await queryClient.prefetchInfiniteQuery({
35 queryKey: ['projects'],
36 queryFn: fetchProjects,
37 defaultPageParam: 0,
38 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
39 pages: 3 // prefetch the first 3 pages
40 })
41}
42```
43[//]: # 'ExampleInfiniteQuery'
44β
45The above code will try to prefetch 3 pages in order, and `getNextPageParam` will be executed for each page to determine the next page to prefetch. If `getNextPageParam` returns `undefined`, the prefetching will stop.
46β
47## Manually Priming a Query
48β
49Alternatively, 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.
50β
51[//]: # 'ExampleSetQueryData'
52β
53```tsx
54queryClient.setQueryData(['todos'], todos)
55```
56β
57[//]: # 'ExampleSetQueryData'
58β
59[//]: # 'Materials'
60β
61## Further reading
62β
63For 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.
64β
65[//]: # 'Materials'