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 wether 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```tsx
35const prefetchTodos = async () => {
36 // The results of this query will be cached like a normal query
37 await queryClient.prefetchQuery({
38 queryKey: ['todos'],
39 queryFn: fetchTodos,
40 })
41}
42```
43β
44Infinite 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:
45β
46```tsx
47const prefetchTodos = async () => {
48 // The results of this query will be cached like a normal query
49 await queryClient.prefetchInfiniteQuery({
50 queryKey: ['projects'],
51 queryFn: fetchProjects,
52 initialPageParam: 0,
53 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
54 pages: 3, // prefetch the first 3 pages
55 })
56}
57```
58β
59Next, let's look at how you can use these and other ways to prefetch in different situations.
60β
61## Prefetch in event handlers
62β
63A 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`.
64β
65```tsx
66function ShowDetailsButton() {
67 const queryClient = useQueryClient()
68β
69 const prefetch = () => {
70 queryClient.prefetchQuery({
71 queryKey: ['details'],
72 queryFn: getDetailsData,
73 // Prefetch only fires when data is older than the staleTime,
74 // so in a case like this you definitely want to set one
75 staleTime: 60000,
76 })
77 }
78β
79 return (
80 <button onMouseEnter={prefetch} onFocus={prefetch} onClick={...}>
81 Show Details
82 </button>
83 )
84}
85```
86β
87## Prefetch in components
88β
89Prefetching 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:
90β
91```tsx
92function Article({ id }) {
93 const { data: articleData, isPending } = useQuery({
94 queryKey: ['article', id],
95 queryFn: getArticleById,
96 })
97β
98 if (isPending) {
99 return 'Loading article...'
100 }
101β
102 return (
103 <>
104 <ArticleHeader articleData={articleData} />
105 <ArticleBody articleData={articleData} />
106 <Comments id={id} />
107 </>
108 )
109}
110β
111function Comments({ id }) {
112 const { data, isPending } = useQuery({
113 queryKey: ['article-comments', id],
114 queryFn: getArticleCommentsById,
115 })
116β
117 ...
118}
119```
120β
121This results in a request waterfall looking like this:
122β
123```
1241. |> getArticleById()
1252. |> getArticleCommentsById()
126```
127β
128As 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?
129β
130In 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:
131β
132```tsx
133function Article({ id }) {
134 const { data: articleData, isPending } = useQuery({
135 queryKey: ['article', id],
136 queryFn: getArticleById,
137 })
138β
139 // Prefetch
140 useQuery({
141 queryKey: ['article-comments', id],
142 queryFn: getArticleCommentsById,
143 // Optional optimization to avoid rerenders when this query changes:
144 notifyOnChangeProps: [],
145 })
146β
147 if (isPending) {
148 return 'Loading article...'
149 }
150β
151 return (
152 <>
153 <ArticleHeader articleData={articleData} />
154 <ArticleBody articleData={articleData} />
155 <Comments id={id} />
156 </>
157 )
158}
159β
160function Comments({ id }) {
161 const { data, isPending } = useQuery({
162 queryKey: ['article-comments', id],
163 queryFn: getArticleCommentsById,
164 })
165β
166 ...
167}
168```
169β
170This starts fetching `'article-comments'` immediately and flattens the waterfall:
171β
172```
1731. |> getArticleById()
1741. |> getArticleCommentsById()
175```
176β
177If 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):
178β
179```tsx
180const usePrefetchQuery = (...args) => {
181 const queryClient = useQueryClient()
182β
183 // This happens in render, but is safe to do because ensureQueryData
184 // only fetches if there is no data in the cache for this query. This
185 // means we know no observers are watching the data so the side effect
186 // is not observable, which is safe.
187 queryClient.ensureQueryData(...args)
188}
189```
190β
191This 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.
192β
193You 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.
194β
195```tsx
196// Prefetch
197usePrefetchQuery({
198 queryKey: ['article-comments', id],
199 queryFn: getArticleCommentsById,
200})
201β
202const { data: articleResult } = useSuspenseQuery({
203 queryKey: ['article', id],
204 queryFn: getArticleById,
205})
206β
207// In nested component:
208const { data: commentsResult } = useSuspenseQuery({
209 queryKey: ['article-comments', id],
210 queryFn: getArticleCommentsById,
211})
212```
213β
214Another 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`:
215β
216```tsx
217const queryClient = useQueryClient()
218const { data: articleData, isPending } = useQuery({
219 queryKey: ['article', id],
220 queryFn: (...args) => {
221 queryClient.prefetchQuery({
222 queryKey: ['article-comments', id],
223 queryFn: getArticleCommentsById,
224 })
225β
226 return getArticleById(...args)
227 },
228})
229```
230β
231Prefetching 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.
232β
233```tsx
234const queryClient = useQueryClient()
235β
236useEffect(() => {
237 queryClient.prefetchQuery({
238 queryKey: ['article-comments', id],
239 queryFn: getArticleCommentsById,
240 })
241}, [queryClient, id])
242```
243β
244To 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:
245β
246- Use `useQuery` or `useSuspenseQueries` and ignore the result
247- Prefetch inside the query function
248- Prefetch in an effect
249β
250Let's look at a slightly more advanced case next.
251β
252### Dependent Queries & Code Splitting
253β
254Sometimes 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):
255β
256```tsx
257// This lazy loads the GraphFeedItem component, meaning
258// it wont start loading until something renders it
259const GraphFeedItem = React.lazy(() => import('./GraphFeedItem'))
260β
261function Feed() {
262 const { data, isPending } = useQuery({
263 queryKey: ['feed'],
264 queryFn: getFeed,
265 })
266β
267 if (isPending) {
268 return 'Loading feed...'
269 }
270β
271 return (
272 <>
273 {data.map((feedItem) => {
274 if (feedItem.type === 'GRAPH') {
275 return <GraphFeedItem key={feedItem.id} feedItem={feedItem} />
276 }
277β
278 return <StandardFeedItem key={feedItem.id} feedItem={feedItem} />
279 })}
280 </>
281 )
282}
283β
284// GraphFeedItem.tsx
285function GraphFeedItem({ feedItem }) {
286 const { data, isPending } = useQuery({
287 queryKey: ['graph', feedItem.id],
288 queryFn: getGraphDataById,
289 })
290β
291 ...
292}
293```
294β
295As noted over in that guide, this example leads to the following double request waterfall:
296β
297```
2981. |> getFeed()
2992. |> JS for <GraphFeedItem>
3003. |> getGraphDataById()
301```
302β
303If 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:
304β
305```tsx
306function Feed() {
307 const queryClient = useQueryClient()
308 const { data, isPending } = useQuery({
309 queryKey: ['feed'],
310 queryFn: async (...args) => {
311 const feed = await getFeed(...args)
312β
313 for (const feedItem of feed) {
314 if (feedItem.type === 'GRAPH') {
315 queryClient.prefetchQuery({
316 queryKey: ['graph', feedItem.id],
317 queryFn: getGraphDataById,
318 })
319 }
320 }
321β
322 return feed
323 }
324 })
325β
326 ...
327}
328```
329β
330This would load the code and data in parallel:
331β
332```
3331. |> getFeed()
3342. |> JS for <GraphFeedItem>
3352. |> getGraphDataById()
336```
337β
338There 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.
339β
340## Router Integration
341β
342Because 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.
343β
344In 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).
345β
346For 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).
347β
348When 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.
349β
350```tsx
351const queryClient = new QueryClient()
352const routerContext = new RouterContext()
353const rootRoute = routerContext.createRootRoute({
354 component: () => { ... }
355})
356β
357const articleRoute = new Route({
358 getParentRoute: () => rootRoute,
359 path: 'article',
360 beforeLoad: () => {
361 return {
362 articleQueryOptions: { queryKey: ['article'], queryFn: fetchArticle },
363 commentsQueryOptions: { queryKey: ['comments'], queryFn: fetchComments },
364 }
365 },
366 loader: async ({
367 context: { queryClient },
368 routeContext: { articleQueryOptions, commentsQueryOptions },
369 }) => {
370 // Fetch comments asap, but don't block
371 queryClient.prefetchQuery(commentsQueryOptions)
372β
373 // Don't render the route at all until article has been fetched
374 await queryClient.prefetchQuery(articleQueryOptions)
375 },
376 component: ({ useRouteContext }) => {
377 const { articleQueryOptions, commentsQueryOptions } = useRouteContext()
378 const articleQuery = useQuery(articleQueryOptions)
379 const commentsQuery = useQuery(commentsQueryOptions)
380β
381 return (
382 ...
383 )
384 },
385 errorComponent: () => 'Oh crap!',
386})
387```
388β
389Integration with other routers is also possible, see the [React Router example](../examples/react/react-router) for another demonstration.
390β
391## Manually Priming a Query
392β
393If 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.
394β
395```tsx
396queryClient.setQueryData(['todos'], todos)
397```
398β
399## Further reading
400β
401For 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.
402β
403Integrating 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).