Open History to see the last commit
1---
2id: prefetching
3title: Prefetching & Router Integration
4---
5β
6When you know or suspect that a certain piece of data will be needed, you can use prefetching to populate the cache with that data ahead of time, leading to a faster experience.
7β
8There are a few different prefetching patterns:
9β
101. In event handlers
112. In components
123. Via router integration
134. During Server Rendering (another form of router integration)
14β
15In this guide, we'll take a look at the first three, while the fourth will be covered in depth in the [Server Rendering & Hydration guide](./ssr.md) and the [Advanced Server Rendering guide](./advanced-ssr.md).
16β
17One specific use of prefetching is to avoid Request Waterfalls, for an in-depth background and explanation of those, see the [Performance & Request Waterfalls guide](./request-waterfalls.md).
18β
19## prefetchQuery & prefetchInfiniteQuery
20β
21Before jumping into the different specific prefetch patterns, let's look at the `prefetchQuery` and `prefetchInfiniteQuery` functions. First a few basics:
22β
23- Out of the box, these functions use the default `staleTime` configured for the `queryClient` to determine whether existing data in the cache is fresh or needs to be fetched again
24- You can also pass a specific `staleTime` like this: `prefetchQuery({ queryKey: ['todos'], queryFn: fn, staleTime: 5000 })`
25 - This `staleTime` is only used for the prefetch, you still need to set it for any `useQuery` call as well
26 - If you want to ignore `staleTime` and instead always return data if it's available in the cache, you can use the `ensureQueryData` function.
27 - Tip: If you are prefetching on the server, set a default `staleTime` higher than `0` for that `queryClient` to avoid having to pass in a specific `staleTime` to each prefetch call
28- If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `gcTime`
29- These functions returns `Promise<void>` and thus never return query data. If that's something you need, use `fetchQuery`/`fetchInfiniteQuery` instead.
30- The prefetch functions never throws errors because they usually try to fetch again in a `useQuery` which is a nice graceful fallback. If you need to catch errors, use `fetchQuery`/`fetchInfiniteQuery` instead.
31β
32This is how you use `prefetchQuery`:
33β
34[//]: # 'ExamplePrefetchQuery'
35β
36```tsx
37const prefetchTodos = async () => {
38 // The results of this query will be cached like a normal query
39 await queryClient.prefetchQuery({
40 queryKey: ['todos'],
41 queryFn: fetchTodos,
42 })
43}
44```
45β
46[//]: # 'ExamplePrefetchQuery'
47β
48Infinite 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:
49β
50[//]: # 'ExamplePrefetchInfiniteQuery'
51β
52```tsx
53const prefetchProjects = async () => {
54 // The results of this query will be cached like a normal query
55 await queryClient.prefetchInfiniteQuery({
56 queryKey: ['projects'],
57 queryFn: fetchProjects,
58 initialPageParam: 0,
59 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
60 pages: 3, // prefetch the first 3 pages
61 })
62}
63```
64β
65[//]: # 'ExamplePrefetchInfiniteQuery'
66β
67Next, let's look at how you can use these and other ways to prefetch in different situations.
68β
69## Prefetch in event handlers
70β
71A straightforward form of prefetching is doing it when the user interacts with something. In this example we'll use `queryClient.prefetchQuery` to start a prefetch on `onMouseEnter` or `onFocus`.
72β
73[//]: # 'ExampleEventHandler'
74β
75```tsx
76function ShowDetailsButton() {
77 const queryClient = useQueryClient()
78β
79 const prefetch = () => {
80 queryClient.prefetchQuery({
81 queryKey: ['details'],
82 queryFn: getDetailsData,
83 // Prefetch only fires when data is older than the staleTime,
84 // so in a case like this you definitely want to set one
85 staleTime: 60000,
86 })
87 }
88β
89 return (
90 <button onMouseEnter={prefetch} onFocus={prefetch} onClick={...}>
91 Show Details
92 </button>
93 )
94}
95```
96β
97[//]: # 'ExampleEventHandler'
98β
99## Prefetch in components
100β
101Prefetching during the component lifecycle is useful when we know some child or descendant will need a particular piece of data, but we can't render that until some other query has finished loading. Let's borrow an example from the Request Waterfall guide to explain:
102β
103[//]: # 'ExampleComponent'
104β
105```tsx
106function Article({ id }) {
107 const { data: articleData, isPending } = useQuery({
108 queryKey: ['article', id],
109 queryFn: getArticleById,
110 })
111β
112 if (isPending) {
113 return 'Loading article...'
114 }
115β
116 return (
117 <>
118 <ArticleHeader articleData={articleData} />
119 <ArticleBody articleData={articleData} />
120 <Comments id={id} />
121 </>
122 )
123}
124β
125function Comments({ id }) {
126 const { data, isPending } = useQuery({
127 queryKey: ['article-comments', id],
128 queryFn: getArticleCommentsById,
129 })
130β
131 ...
132}
133```
134β
135[//]: # 'ExampleComponent'
136β
137This results in a request waterfall looking like this:
138β
139```
1401. |> getArticleById()
1412. |> getArticleCommentsById()
142```
143β
144As mentioned in that guide, one way to flatten this waterfall and improve performance is to hoist the `getArticleCommentsById` query to the parent and pass down the result as a prop, but what if this is not feasible or desirable, for example when the components are unrelated and have multiple levels between them?
145β
146In that case, we can instead prefetch the query in the parent. The simplest way to do this is to use a query but ignore the result:
147β
148[//]: # 'ExampleParentComponent'
149β
150```tsx
151function Article({ id }) {
152 const { data: articleData, isPending } = useQuery({
153 queryKey: ['article', id],
154 queryFn: getArticleById,
155 })
156β
157 // Prefetch
158 useQuery({
159 queryKey: ['article-comments', id],
160 queryFn: getArticleCommentsById,
161 // Optional optimization to avoid rerenders when this query changes:
162 notifyOnChangeProps: [],
163 })
164β
165 if (isPending) {
166 return 'Loading article...'
167 }
168β
169 return (
170 <>
171 <ArticleHeader articleData={articleData} />
172 <ArticleBody articleData={articleData} />
173 <Comments id={id} />
174 </>
175 )
176}
177β
178function Comments({ id }) {
179 const { data, isPending } = useQuery({
180 queryKey: ['article-comments', id],
181 queryFn: getArticleCommentsById,
182 })
183β
184 ...
185}
186```
187β
188[//]: # 'ExampleParentComponent'
189β
190This starts fetching `'article-comments'` immediately and flattens the waterfall:
191β
192```
1931. |> getArticleById()
1941. |> getArticleCommentsById()
195```
196β
197[//]: # 'Suspense'
198β
199If you want to prefetch together with Suspense, you will have to do things a bit differently. You can't use `useSuspenseQueries` to prefetch, since the prefetch would block the component from rendering. You also can not use `useQuery` for the prefetch, because that wouldn't start the prefetch until after suspenseful query had resolved. For this scenario, you can use the [`usePrefetchQuery`](../reference/usePrefetchQuery.md) or the [`usePrefetchInfiniteQuery`](../reference/usePrefetchInfiniteQuery.md) hooks available in the library.
200β
201You can now use `useSuspenseQuery` in the component that actually needs the data. You _might_ want to wrap this later component in its own `<Suspense>` boundary so the "secondary" query we are prefetching does not block rendering of the "primary" data.
202β
203```tsx
204function ArticleLayout({ id }) {
205 usePrefetchQuery({
206 queryKey: ['article-comments', id],
207 queryFn: getArticleCommentsById,
208 })
209β
210 return (
211 <Suspense fallback="Loading article">
212 <Article id={id} />
213 </Suspense>
214 )
215}
216β
217function Article({ id }) {
218 const { data: articleData, isPending } = useSuspenseQuery({
219 queryKey: ['article', id],
220 queryFn: getArticleById,
221 })
222β
223 ...
224}
225```
226β
227Another way is to prefetch inside of the query function. This makes sense if you know that every time an article is fetched it's very likely comments will also be needed. For this, we'll use `queryClient.prefetchQuery`:
228β
229```tsx
230const queryClient = useQueryClient()
231const { data: articleData, isPending } = useQuery({
232 queryKey: ['article', id],
233 queryFn: (...args) => {
234 queryClient.prefetchQuery({
235 queryKey: ['article-comments', id],
236 queryFn: getArticleCommentsById,
237 })
238β
239 return getArticleById(...args)
240 },
241})
242```
243β
244Prefetching in an effect also works, but note that if you are using `useSuspenseQuery` in the same component, this effect wont run until _after_ the query finishes which might not be what you want.
245β
246```tsx
247const queryClient = useQueryClient()
248β
249useEffect(() => {
250 queryClient.prefetchQuery({
251 queryKey: ['article-comments', id],
252 queryFn: getArticleCommentsById,
253 })
254}, [queryClient, id])
255```
256β
257To recap, if you want to prefetch a query during the component lifecycle, there are a few different ways to do it, pick the one that suits your situation best:
258β
259- Prefetch before a suspense boundary using `usePrefetchQuery` or `usePrefetchInfiniteQuery` hooks
260- Use `useQuery` or `useSuspenseQueries` and ignore the result
261- Prefetch inside the query function
262- Prefetch in an effect
263β
264Let's look at a slightly more advanced case next.
265β
266[//]: # 'Suspense'
267β
268### Dependent Queries & Code Splitting
269β
270Sometimes we want to prefetch conditionally, based on the result of another fetch. Consider this example borrowed from the [Performance & Request Waterfalls guide](./request-waterfalls.md):
271β
272[//]: # 'ExampleConditionally1'
273β
274```tsx
275// This lazy loads the GraphFeedItem component, meaning
276// it wont start loading until something renders it
277const GraphFeedItem = React.lazy(() => import('./GraphFeedItem'))
278β
279function Feed() {
280 const { data, isPending } = useQuery({
281 queryKey: ['feed'],
282 queryFn: getFeed,
283 })
284β
285 if (isPending) {
286 return 'Loading feed...'
287 }
288β
289 return (
290 <>
291 {data.map((feedItem) => {
292 if (feedItem.type === 'GRAPH') {
293 return <GraphFeedItem key={feedItem.id} feedItem={feedItem} />
294 }
295β
296 return <StandardFeedItem key={feedItem.id} feedItem={feedItem} />
297 })}
298 </>
299 )
300}
301β
302// GraphFeedItem.tsx
303function GraphFeedItem({ feedItem }) {
304 const { data, isPending } = useQuery({
305 queryKey: ['graph', feedItem.id],
306 queryFn: getGraphDataById,
307 })
308β
309 ...
310}
311```
312β
313[//]: # 'ExampleConditionally1'
314β
315As noted over in that guide, this example leads to the following double request waterfall:
316β
317```
3181. |> getFeed()
3192. |> JS for <GraphFeedItem>
3203. |> getGraphDataById()
321```
322β
323If we can not restructure our API so `getFeed()` also returns the `getGraphDataById()` data when necessary, there is no way to get rid of the `getFeed->getGraphDataById` waterfall, but by leveraging conditional prefetching, we can at least load the code and data in parallel. Just like described above, there are multiple ways to do this, but for this example, we'll do it in the query function:
324β
325[//]: # 'ExampleConditionally2'
326β
327```tsx
328function Feed() {
329 const queryClient = useQueryClient()
330 const { data, isPending } = useQuery({
331 queryKey: ['feed'],
332 queryFn: async (...args) => {
333 const feed = await getFeed(...args)
334β
335 for (const feedItem of feed) {
336 if (feedItem.type === 'GRAPH') {
337 queryClient.prefetchQuery({
338 queryKey: ['graph', feedItem.id],
339 queryFn: getGraphDataById,
340 })
341 }
342 }
343β
344 return feed
345 }
346 })
347β
348 ...
349}
350```
351β
352[//]: # 'ExampleConditionally2'
353β
354This would load the code and data in parallel:
355β
356```
3571. |> getFeed()
3582. |> JS for <GraphFeedItem>
3592. |> getGraphDataById()
360```
361β
362There is a tradeoff however, in that the code for `getGraphDataById` is now included in the parent bundle instead of in `JS for <GraphFeedItem>` so you'll need to determine what's the best performance tradeoff on a case by case basis. If `GraphFeedItem` are likely, it's probably worth to include the code in the parent. If they are exceedingly rare, it's probably not.
363β
364[//]: # 'Router'
365β
366## Router Integration
367β
368Because data fetching in the component tree itself can easily lead to request waterfalls and the different fixes for that can be cumbersome as they accumulate throughout the application, an attractive way to do prefetching is integrating it at the router level.
369β
370In this approach, you explicitly declare for each _route_ what data is going to be needed for that component tree, ahead of time. Because Server Rendering has traditionally needed all data to be loaded before rendering starts, this has been the dominating approach for SSR'd apps for a long time. This is still a common approach and you can read more about it in the [Server Rendering & Hydration guide](./ssr.md).
371β
372For now, let's focus on the client side case and look at an example of how you can make this work with [Tanstack Router](https://tanstack.com/router). These examples leave out a lot of setup and boilerplate to stay concise, you can check out a [full React Query example](https://tanstack.com/router/.latest/docs/framework/react/examples/basic-react-query-file-based) over in the [Tanstack Router docs](https://tanstack.com/router/latest/docs).
373β
374When integrating at the router level, you can choose to either _block_ rendering of that route until all data is present, or you can start a prefetch but not await the result. That way, you can start rendering the route as soon as possible. You can also mix these two approaches and await some critical data, but start rendering before all the secondary data has finished loading. In this example, we'll configure an `/article` route to not render until the article data has finished loading, as well as start prefetching comments as soon as possible, but not block rendering the route if comments haven't finished loading yet.
375β
376```tsx
377const queryClient = new QueryClient()
378const routerContext = new RouterContext()
379const rootRoute = routerContext.createRootRoute({
380 component: () => { ... }
381})
382β
383const articleRoute = new Route({
384 getParentRoute: () => rootRoute,
385 path: 'article',
386 beforeLoad: () => {
387 return {
388 articleQueryOptions: { queryKey: ['article'], queryFn: fetchArticle },
389 commentsQueryOptions: { queryKey: ['comments'], queryFn: fetchComments },
390 }
391 },
392 loader: async ({
393 context: { queryClient },
394 routeContext: { articleQueryOptions, commentsQueryOptions },
395 }) => {
396 // Fetch comments asap, but don't block
397 queryClient.prefetchQuery(commentsQueryOptions)
398β
399 // Don't render the route at all until article has been fetched
400 await queryClient.prefetchQuery(articleQueryOptions)
401 },
402 component: ({ useRouteContext }) => {
403 const { articleQueryOptions, commentsQueryOptions } = useRouteContext()
404 const articleQuery = useQuery(articleQueryOptions)
405 const commentsQuery = useQuery(commentsQueryOptions)
406β
407 return (
408 ...
409 )
410 },
411 errorComponent: () => 'Oh crap!',
412})
413```
414β
415Integration with other routers is also possible, see the [React Router example](../examples/react/react-router) for another demonstration.
416β
417[//]: # 'Router'
418β
419## Manually Priming a Query
420β
421If 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.md#queryclientsetquerydata) to directly add or update a query's cached result by key.
422β
423[//]: # 'ExampleManualPriming'
424β
425```tsx
426queryClient.setQueryData(['todos'], todos)
427```
428β
429[//]: # 'ExampleManualPriming'
430[//]: # 'Materials'
431β
432## Further reading
433β
434For 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.md#17-seeding-the-query-cache) from the Community Resources.
435β
436Integrating with Server Side routers and frameworks is very similar to what we just saw, with the addition that the data has to passed from the server to the client to be hydrated into the cache there. To learn how, continue on to the [Server Rendering & Hydration guide](./ssr.md).
437β
438[//]: # 'Materials'