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## Using `query` to prefetch
20β
21> [!NOTE]
22> These tips replace the use of the now deprecated `prefetchQuery` and `ensureQueryData` methods. If you used an earlier version of this guide, note that those methods will be removed in the next major version of TanStack Query
23β
24Prefetching a query uses the `query` method. This method by default will
25β
26- Run the query function
27- Cache the result
28- Return the result of that query
29- Throw if it hits any errors
30β
31For prefetching you often want to modify these defaults:
32β
33- Out of the box, `query` uses the default `staleTime` configured for the `queryClient` to determine whether existing data in the cache is fresh or needs to be fetched again
34- You can also pass a specific `staleTime` like this: `query({ queryKey: ['todos'], queryFn: fn, staleTime: 5 * 1000 })`
35 - This `staleTime` is only used for that query fetch, you still need to set it for any `useQuery` call as well
36 - If you want to always return data if it's available in the cache regardless of the default `staleTime`, you can pass `"static"` in for `staleTime`.
37 - 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
38- If no instances of `useQuery` appear for a prefetched query, it will be deleted and garbage collected after the time specified in `gcTime`
39- If your prefetch is for non-critical data, you can discard the promise with `void` and use `.catch(noop)` to swallow errors. The query will usually try to fetch again in a `useQuery`, which is a nice graceful fallback.
40β
41This is how you use `query` to prefetch:
42β
43[//]: # 'ExamplePrefetchQuery'
44β
45```tsx
46import { noop } from '@tanstack/react-query'
47β
48const prefetchTodos = async () => {
49 await queryClient
50 .query({
51 queryKey: ['todos'],
52 queryFn: fetchTodos,
53 // Swallow errors here, because usually they will fetch again in `useQuery`
54 })
55 .catch(noop)
56}
57```
58β
59[//]: # 'ExamplePrefetchQuery'
60β
61Infinite Queries can be prefetched like regular Queries. By 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:
62β
63[//]: # 'ExamplePrefetchInfiniteQuery'
64β
65```tsx
66import { noop } from '@tanstack/react-query'
67β
68const prefetchProjects = () => {
69 await queryClient
70 .infiniteQuery({
71 queryKey: ['projects'],
72 queryFn: fetchProjects,
73 initialPageParam: 0,
74 getNextPageParam: (lastPage, pages) => lastPage.nextCursor,
75 pages: 3, // prefetch the first 3 pages
76 })
77 .catch(noop)
78}
79```
80β
81[//]: # 'ExamplePrefetchInfiniteQuery'
82β
83Next, let's look at how you can use these and other ways to prefetch in different situations.
84β
85## Prefetch in event handlers
86β
87A straightforward form of prefetching is doing it when the user interacts with something. In this example we'll use `queryClient.query` to start a prefetch on `onMouseEnter` or `onFocus`.
88β
89[//]: # 'ExampleEventHandler'
90β
91```tsx
92function ShowDetailsButton() {
93 const queryClient = useQueryClient()
94β
95 const prefetch = () => {
96 void queryClient.query({
97 queryKey: ['details'],
98 queryFn: getDetailsData,
99 // Prefetch only fires when data is older than the staleTime,
100 // so in a case like this you definitely want to set one
101 staleTime: 60 * 1000,
102 }).catch(noop)
103 }
104β
105 return (
106 <button onMouseEnter={prefetch} onFocus={prefetch} onClick={...}>
107 Show Details
108 </button>
109 )
110}
111```
112β
113[//]: # 'ExampleEventHandler'
114β
115## Prefetch in components
116β
117Prefetching 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:
118β
119[//]: # 'ExampleComponent'
120β
121```tsx
122function Article({ id }) {
123 const { data: articleData, isPending } = useQuery({
124 queryKey: ['article', id],
125 queryFn: getArticleById,
126 })
127β
128 if (isPending) {
129 return 'Loading article...'
130 }
131β
132 return (
133 <>
134 <ArticleHeader articleData={articleData} />
135 <ArticleBody articleData={articleData} />
136 <Comments id={id} />
137 </>
138 )
139}
140β
141function Comments({ id }) {
142 const { data, isPending } = useQuery({
143 queryKey: ['article-comments', id],
144 queryFn: getArticleCommentsById,
145 })
146β
147 ...
148}
149```
150β
151[//]: # 'ExampleComponent'
152β
153This results in a request waterfall looking like this:
154β
155```
1561. |> getArticleById()
1572. |> getArticleCommentsById()
158```
159β
160As 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?
161β
162In 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:
163β
164[//]: # 'ExampleParentComponent'
165β
166```tsx
167function Article({ id }) {
168 const { data: articleData, isPending } = useQuery({
169 queryKey: ['article', id],
170 queryFn: getArticleById,
171 })
172β
173 // Prefetch
174 useQuery({
175 queryKey: ['article-comments', id],
176 queryFn: getArticleCommentsById,
177 // Optional optimization to avoid rerenders when this query changes:
178 notifyOnChangeProps: [],
179 })
180β
181 if (isPending) {
182 return 'Loading article...'
183 }
184β
185 return (
186 <>
187 <ArticleHeader articleData={articleData} />
188 <ArticleBody articleData={articleData} />
189 <Comments id={id} />
190 </>
191 )
192}
193β
194function Comments({ id }) {
195 const { data, isPending } = useQuery({
196 queryKey: ['article-comments', id],
197 queryFn: getArticleCommentsById,
198 })
199β
200 ...
201}
202```
203β
204[//]: # 'ExampleParentComponent'
205β
206This starts fetching `'article-comments'` immediately and flattens the waterfall:
207β
208```
2091. |> getArticleById()
2101. |> getArticleCommentsById()
211```
212β
213[//]: # 'Suspense'
214β
215If 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/functions/usePrefetchQuery.md) or the [`usePrefetchInfiniteQuery`](../reference/functions/usePrefetchInfiniteQuery.md) hooks available in the library.
216β
217You 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.
218β
219```tsx
220function ArticleLayout({ id }) {
221 usePrefetchQuery({
222 queryKey: ['article-comments', id],
223 queryFn: getArticleCommentsById,
224 })
225β
226 return (
227 <Suspense fallback="Loading article">
228 <Article id={id} />
229 </Suspense>
230 )
231}
232β
233function Article({ id }) {
234 const { data: articleData, isPending } = useSuspenseQuery({
235 queryKey: ['article', id],
236 queryFn: getArticleById,
237 })
238β
239 ...
240}
241```
242β
243Another way is to prefetch inside 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.query`:
244β
245```tsx
246const queryClient = useQueryClient()
247const { data: articleData, isPending } = useQuery({
248 queryKey: ['article', id],
249 queryFn: (...args) => {
250 void queryClient
251 .query({
252 queryKey: ['article-comments', id],
253 queryFn: getArticleCommentsById,
254 })
255 .catch(noop)
256β
257 return getArticleById(...args)
258 },
259})
260```
261β
262Prefetching in an effect also works, but note that if you are using `useSuspenseQuery` in the same component, this effect won't run until _after_ the query finishes which might not be what you want.
263β
264```tsx
265const queryClient = useQueryClient()
266β
267useEffect(() => {
268 void queryClient
269 .query({
270 queryKey: ['article-comments', id],
271 queryFn: getArticleCommentsById,
272 })
273 .catch(noop)
274}, [queryClient, id])
275```
276β
277To 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:
278β
279- Prefetch before a suspense boundary using `usePrefetchQuery` or `usePrefetchInfiniteQuery` hooks
280- Use `useQuery` or `useSuspenseQueries` and ignore the result
281- Prefetch inside the query function
282- Prefetch in an effect
283β
284Let's look at a slightly more advanced case next.
285β
286[//]: # 'Suspense'
287β
288### Dependent Queries & Code Splitting
289β
290Sometimes 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):
291β
292[//]: # 'ExampleConditionally1'
293β
294```tsx
295// This lazy loads the GraphFeedItem component, meaning
296// it won't start loading until something renders it
297const GraphFeedItem = React.lazy(() => import('./GraphFeedItem'))
298β
299function Feed() {
300 const { data, isPending } = useQuery({
301 queryKey: ['feed'],
302 queryFn: getFeed,
303 })
304β
305 if (isPending) {
306 return 'Loading feed...'
307 }
308β
309 return (
310 <>
311 {data.map((feedItem) => {
312 if (feedItem.type === 'GRAPH') {
313 return <GraphFeedItem key={feedItem.id} feedItem={feedItem} />
314 }
315β
316 return <StandardFeedItem key={feedItem.id} feedItem={feedItem} />
317 })}
318 </>
319 )
320}
321β
322// GraphFeedItem.tsx
323function GraphFeedItem({ feedItem }) {
324 const { data, isPending } = useQuery({
325 queryKey: ['graph', feedItem.id],
326 queryFn: getGraphDataById,
327 })
328β
329 ...
330}
331```
332β
333[//]: # 'ExampleConditionally1'
334β
335As noted over in that guide, this example leads to the following double request waterfall:
336β
337```
3381. |> getFeed()
3392. |> JS for <GraphFeedItem>
3403. |> getGraphDataById()
341```
342β
343If 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:
344β
345[//]: # 'ExampleConditionally2'
346β
347```tsx
348function Feed() {
349 const queryClient = useQueryClient()
350 const { data, isPending } = useQuery({
351 queryKey: ['feed'],
352 queryFn: async (...args) => {
353 const feed = await getFeed(...args)
354β
355 for (const feedItem of feed) {
356 if (feedItem.type === 'GRAPH') {
357 void queryClient.query({
358 queryKey: ['graph', feedItem.id],
359 queryFn: getGraphDataById,
360 }).catch(noop)
361 }
362 }
363β
364 return feed
365 }
366 })
367β
368 ...
369}
370```
371β
372[//]: # 'ExampleConditionally2'
373β
374This would load the code and data in parallel:
375β
376```
3771. |> getFeed()
3782. |> JS for <GraphFeedItem>
3792. |> getGraphDataById()
380```
381β
382There 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.
383β
384[//]: # 'Router'
385β
386## Router Integration
387β
388Because 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.
389β
390In 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).
391β
392For 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).
393β
394When 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.
395β
396Note that many route loaders use error boundaries to trigger error fallbacks. Whereas up to now we have been using `.catch(noop)` to ignore errors for data that will be retried by `useQuery`, for critical data that the route will not work without, you should `await` the promise without `noop` and handle the error in a `try` block or the router's error handling (such as TanStack Router's `errorComponent`).
397β
398```tsx
399const queryClient = new QueryClient()
400const routerContext = new RouterContext()
401const rootRoute = routerContext.createRootRoute({
402 component: () => { ... }
403})
404β
405const articleRoute = new Route({
406 getParentRoute: () => rootRoute,
407 path: 'article',
408 beforeLoad: () => {
409 return {
410 articleQueryOptions: { queryKey: ['article'], queryFn: fetchArticle },
411 commentsQueryOptions: { queryKey: ['comments'], queryFn: fetchComments },
412 }
413 },
414 loader: async ({
415 context: { queryClient },
416 routeContext: { articleQueryOptions, commentsQueryOptions },
417 }) => {
418 // Fetch comments asap, but don't block or throw errors
419 void queryClient.query(commentsQueryOptions).catch(noop)
420β
421 // Don't render the route at all until article has been fetched
422 // As this is critical data we want the error component to trigger
423 // as soon as possible if something goes wrong
424 await queryClient.query({
425 ...articleQueryOptions,
426 // If we have the article loaded already, we don't want to block on
427 // an extra prefetch; fallback on the default useQuery behavior to
428 // keep the data fresh
429 staleTime: 'static'
430 })
431 },
432 component: ({ useRouteContext }) => {
433 const { articleQueryOptions, commentsQueryOptions } = useRouteContext()
434 const articleQuery = useQuery(articleQueryOptions)
435 const commentsQuery = useQuery(commentsQueryOptions)
436β
437 return (
438 ...
439 )
440 },
441 errorComponent: () => 'Oh crap!',
442})
443```
444β
445Integration with other routers is also possible, see the [contacts-react-router](../examples/contacts-react-router) for another demonstration.
446β
447[//]: # 'Router'
448β
449## Manually Priming a Query
450β
451If 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/classes/QueryClient.md#setquerydata) to directly add or update a query's cached result by key.
452β
453[//]: # 'ExampleManualPriming'
454β
455```tsx
456queryClient.setQueryData(['todos'], todos)
457```
458β
459[//]: # 'ExampleManualPriming'
460[//]: # 'Materials'
461β
462## Further reading
463β
464For a deep-dive on how to get data into your Query Cache before you fetch, see the [article Seeding the Query Cache by TkDodo](https://tkdodo.eu/blog/seeding-the-query-cache).
465β
466Integrating with Server Side routers and frameworks is very similar to what we just saw, with the addition that the data has to be 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).
467β
468[//]: # 'Materials'