|
1 | 1 | --- |
2 | 2 | id: prefetching |
3 | 3 | title: Prefetching |
4 | | -ref: docs/react/guides/prefetching.md |
5 | 4 | --- |
| 5 | + |
| 6 | +If 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 |
| 11 | +const 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 | + |
| 28 | +Infinite 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 | + |
| 32 | +```tsx |
| 33 | +const prefetchTodos = async () => { |
| 34 | + // The results of this query will be cached like a normal query |
| 35 | + await queryClient.prefetchInfiniteQuery({ |
| 36 | + queryKey: ['projects'], |
| 37 | + queryFn: fetchProjects, |
| 38 | + initialPageParam: 0, |
| 39 | + getNextPageParam: (lastPage, pages) => lastPage.nextCursor, |
| 40 | + pages: 3, // prefetch the first 3 pages |
| 41 | + }) |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +[//]: # 'ExampleInfiniteQuery' |
| 46 | + |
| 47 | +The 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. |
0 commit comments