Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

prefetching.md

468 lines16.7 KB

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)
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)
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 )
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 )
140​
141function Comments({ id }) {
142 const { data, isPending } = useQuery({
143 queryKey: ['article-comments', id],
144 queryFn: getArticleCommentsById,
145 })
146​
147 ...
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 )
193​
194function Comments({ id }) {
195 const { data, isPending } = useQuery({
196 queryKey: ['article-comments', id],
197 queryFn: getArticleCommentsById,
198 })
199​
200 ...
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 )
232​
233function Article({ id }) {
234 const { data: articleData, isPending } = useSuspenseQuery({
235 queryKey: ['article', id],
236 queryFn: getArticleById,
237 })
238​
239 ...
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 )
321​
322// GraphFeedItem.tsx
323function GraphFeedItem({ feedItem }) {
324 const { data, isPending } = useQuery({
325 queryKey: ['graph', feedItem.id],
326 queryFn: getGraphDataById,
327 })
328​
329 ...
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 ...
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'