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](./guides/ssr) and the [Advanced Server Rendering guide](./guides/advanced-ssr).
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](./guides/request-waterfalls).
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 prefetchTodos = 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. What you can do is add a small `usePrefetchQuery` function (we might add this to the library itself at a later point):
200β
201```tsx
202const usePrefetchQuery = (...args) => {
203 const queryClient = useQueryClient()
204β
205 // This happens in render, but is safe to do because ensureQueryData
206 // only fetches if there is no data in the cache for this query. This
207 // means we know no observers are watching the data so the side effect
208 // is not observable, which is safe.
209 queryClient.ensureQueryData(...args)
210}
211```
212β
213This approach works with both `useQuery` and `useSuspenseQuery`, so feel free to use it as an alternative to the `useQuery({ ..., notifyOnChangeProps: [] })` approach as well. The only tradeoff is that the above function will never fetch and _update_ existing data in the cache if it's stale, but this will usually happen in the later query anyway.
214β
215You 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.
216β
217```tsx
218// Prefetch
219usePrefetchQuery({
220 queryKey: ['article-comments', id],
221 queryFn: getArticleCommentsById,
222})
223β
224const { data: articleResult } = useSuspenseQuery({
225 queryKey: ['article', id],
226 queryFn: getArticleById,
227})
228β
229// In nested component:
230const { data: commentsResult } = useSuspenseQuery({
231 queryKey: ['article-comments', id],
232 queryFn: getArticleCommentsById,
233})
234```
235β
236Another 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`:
237β
238```tsx
239const queryClient = useQueryClient()
240const { data: articleData, isPending } = useQuery({
241 queryKey: ['article', id],
242 queryFn: (...args) => {
243 queryClient.prefetchQuery({
244 queryKey: ['article-comments', id],
245 queryFn: getArticleCommentsById,
246 })
247β
248 return getArticleById(...args)
249 },
250})
251```
252β
253Prefetching 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.
254β
255```tsx
256const queryClient = useQueryClient()
257β
258useEffect(() => {
259 queryClient.prefetchQuery({
260 queryKey: ['article-comments', id],
261 queryFn: getArticleCommentsById,
262 })
263}, [queryClient, id])
264```
265β
266To 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:
267β
268- Use `useQuery` or `useSuspenseQueries` and ignore the result
269- Prefetch inside the query function
270- Prefetch in an effect
271β
272Let's look at a slightly more advanced case next.
273β
274[//]: # 'Suspense'
275β
276### Dependent Queries & Code Splitting
277β
278Sometimes we want to prefetch conditionally, based on the result of another fetch. Consider this example borrowed from the [Performance & Request Waterfalls guide](./guides/request-waterfalls):
279β
280[//]: # 'ExampleConditionally1'
281β
282```tsx
283// This lazy loads the GraphFeedItem component, meaning
284// it wont start loading until something renders it
285const GraphFeedItem = React.lazy(() => import('./GraphFeedItem'))
286β
287function Feed() {
288 const { data, isPending } = useQuery({
289 queryKey: ['feed'],
290 queryFn: getFeed,
291 })
292β
293 if (isPending) {
294 return 'Loading feed...'
295 }
296β
297 return (
298 <>
299 {data.map((feedItem) => {
300 if (feedItem.type === 'GRAPH') {
301 return <GraphFeedItem key={feedItem.id} feedItem={feedItem} />
302 }
303β
304 return <StandardFeedItem key={feedItem.id} feedItem={feedItem} />
305 })}
306 </>
307 )
308}
309β
310// GraphFeedItem.tsx
311function GraphFeedItem({ feedItem }) {
312 const { data, isPending } = useQuery({
313 queryKey: ['graph', feedItem.id],
314 queryFn: getGraphDataById,
315 })
316β
317 ...
318}
319```
320β
321[//]: # 'ExampleConditionally1'
322β
323As noted over in that guide, this example leads to the following double request waterfall:
324β
325```
3261. |> getFeed()
3272. |> JS for <GraphFeedItem>
3283. |> getGraphDataById()
329```
330β
331If 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:
332β
333[//]: # 'ExampleConditionally2'
334β
335```tsx
336function Feed() {
337 const queryClient = useQueryClient()
338 const { data, isPending } = useQuery({
339 queryKey: ['feed'],
340 queryFn: async (...args) => {
341 const feed = await getFeed(...args)
342β
343 for (const feedItem of feed) {
344 if (feedItem.type === 'GRAPH') {
345 queryClient.prefetchQuery({
346 queryKey: ['graph', feedItem.id],
347 queryFn: getGraphDataById,
348 })
349 }
350 }
351β
352 return feed
353 }
354 })
355β
356 ...
357}
358```
359β
360[//]: # 'ExampleConditionally2'
361β
362This would load the code and data in parallel:
363β
364```
3651. |> getFeed()
3662. |> JS for <GraphFeedItem>
3672. |> getGraphDataById()
368```
369β
370There 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.
371β
372[//]: # 'Router'
373β
374## Router Integration
375β
376Because 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.
377β
378In 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](./guides/ssr).
379β
380For 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/v1/docs/examples/react/with-react-query?file=src%2Fmain.tsx) over in the [Tanstack Router docs](https://tanstack.com/router/v1/docs).
381β
382When 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.
383β
384```tsx
385const queryClient = new QueryClient()
386const routerContext = new RouterContext()
387const rootRoute = routerContext.createRootRoute({
388 component: () => { ... }
389})
390β
391const articleRoute = new Route({
392 getParentRoute: () => rootRoute,
393 path: 'article',
394 beforeLoad: () => {
395 return {
396 articleQueryOptions: { queryKey: ['article'], queryFn: fetchArticle },
397 commentsQueryOptions: { queryKey: ['comments'], queryFn: fetchComments },
398 }
399 },
400 loader: async ({
401 context: { queryClient },
402 routeContext: { articleQueryOptions, commentsQueryOptions },
403 }) => {
404 // Fetch comments asap, but don't block
405 queryClient.prefetchQuery(commentsQueryOptions)
406β
407 // Don't render the route at all until article has been fetched
408 await queryClient.prefetchQuery(articleQueryOptions)
409 },
410 component: ({ useRouteContext }) => {
411 const { articleQueryOptions, commentsQueryOptions } = useRouteContext()
412 const articleQuery = useQuery(articleQueryOptions)
413 const commentsQuery = useQuery(commentsQueryOptions)
414β
415 return (
416 ...
417 )
418 },
419 errorComponent: () => 'Oh crap!',
420})
421```
422β
423Integration with other routers is also possible, see the [React Router example](./examples/react-router) for another demonstration.
424β
425[//]: # 'Router'
426β
427## Manually Priming a Query
428β
429If 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.
430β
431[//]: # 'ExampleManualPriming'
432β
433```tsx
434queryClient.setQueryData(['todos'], todos)
435```
436β
437[//]: # 'ExampleManualPriming'
438[//]: # 'Materials'
439β
440## Further reading
441β
442For 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.
443β
444Integrating 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](./guides/ssr).
445β
446[//]: # 'Materials'