Open History to see the last commit
1---
2id: prefetching
3title: Prefetching & Router Integration
4ref: docs/framework/react/guides/prefetching.md
5replace: { 'react-query': 'solid-query', 'React': 'Solid' }
6---
7β
8[//]: # 'ExampleComponent'
9β
10```tsx
11import { Switch, Match } from 'solid-js'
12β
13function Article(props) {
14 const articleQuery = useQuery(() => ({
15 queryKey: ['article', props.id],
16 queryFn: getArticleById,
17 }))
18β
19 return (
20 <Switch>
21 <Match when={articleQuery.isPending}>
22 Loading article...
23 </Match>
24 <Match when={articleQuery.isSuccess}>
25 <ArticleHeader articleData={articleQuery.data} />
26 <ArticleBody articleData={articleQuery.data} />
27 <Comments id={props.id} />
28 </Match>
29 </Switch>
30 )
31}
32β
33function Comments(props) {
34 const commentsQuery = useQuery(() => ({
35 queryKey: ['article-comments', props.id],
36 queryFn: getArticleCommentsById,
37 }))
38β
39 ...
40}
41```
42β
43[//]: # 'ExampleComponent'
44[//]: # 'ExampleParentComponent'
45β
46```tsx
47import { Switch, Match } from 'solid-js'
48β
49function Article(props) {
50 const articleQuery = useQuery(() => ({
51 queryKey: ['article', props.id],
52 queryFn: getArticleById,
53 }))
54β
55 // Prefetch
56 useQuery(() => ({
57 queryKey: ['article-comments', props.id],
58 queryFn: getArticleCommentsById,
59 // Optional optimization to avoid rerenders when this query changes:
60 notifyOnChangeProps: [],
61 }))
62β
63 return (
64 <Switch>
65 <Match when={articleQuery.isPending}>
66 Loading article...
67 </Match>
68 <Match when={articleQuery.isSuccess}>
69 <ArticleHeader articleData={articleQuery.data} />
70 <ArticleBody articleData={articleQuery.data} />
71 <Comments id={props.id} />
72 </Match>
73 </Switch>
74 )
75}
76β
77function Comments(props) {
78 const commentsQuery = useQuery(() => ({
79 queryKey: ['article-comments', props.id],
80 queryFn: getArticleCommentsById,
81 }))
82β
83 ...
84}
85```
86β
87[//]: # 'ExampleParentComponent'
88[//]: # 'Suspense'
89β
90Another 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`:
91β
92```tsx
93const queryClient = useQueryClient()
94const articleQuery = useQuery(() => ({
95 queryKey: ['article', id],
96 queryFn: (...args) => {
97 void queryClient
98 .query({
99 queryKey: ['article-comments', id],
100 queryFn: getArticleCommentsById,
101 })
102 .catch(noop)
103β
104 return getArticleById(...args)
105 },
106}))
107```
108β
109Prefetching in an effect also works:
110β
111```tsx
112import { createEffect } from 'solid-js'
113β
114const queryClient = useQueryClient()
115β
116createEffect(() => {
117 void queryClient
118 .query({
119 queryKey: ['article-comments', id],
120 queryFn: getArticleCommentsById,
121 })
122 .catch(noop)
123})
124```
125β
126To 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:
127β
128- Use `useQuery` and ignore the result
129- Prefetch inside the query function
130- Prefetch in an effect
131β
132Let's look at a slightly more advanced case next.
133β
134[//]: # 'Suspense'
135[//]: # 'ExampleConditionally1'
136β
137```tsx
138import { lazy, Switch, Match, For } from 'solid-js'
139β
140// This lazy loads the GraphFeedItem component, meaning
141// it won't start loading until something renders it
142const GraphFeedItem = lazy(() => import('./GraphFeedItem'))
143β
144function Feed() {
145 const feedQuery = useQuery(() => ({
146 queryKey: ['feed'],
147 queryFn: getFeed,
148 }))
149β
150 return (
151 <Switch>
152 <Match when={feedQuery.isPending}>
153 Loading feed...
154 </Match>
155 <Match when={feedQuery.isSuccess}>
156 <For each={feedQuery.data}>
157 {(feedItem) => {
158 if (feedItem.type === 'GRAPH') {
159 return <GraphFeedItem feedItem={feedItem} />
160 }
161 return <StandardFeedItem feedItem={feedItem} />
162 }}
163 </For>
164 </Match>
165 </Switch>
166 )
167}
168β
169// GraphFeedItem.tsx
170function GraphFeedItem(props) {
171 const graphQuery = useQuery(() => ({
172 queryKey: ['graph', props.feedItem.id],
173 queryFn: getGraphDataById,
174 }))
175β
176 ...
177}
178```
179β
180[//]: # 'ExampleConditionally1'
181[//]: # 'ExampleConditionally2'
182β
183```tsx
184function Feed() {
185 const queryClient = useQueryClient()
186 const feedQuery = useQuery(() => ({
187 queryKey: ['feed'],
188 queryFn: async (...args) => {
189 const feed = await getFeed(...args)
190β
191 for (const feedItem of feed) {
192 if (feedItem.type === 'GRAPH') {
193 void queryClient.query({
194 queryKey: ['graph', feedItem.id],
195 queryFn: getGraphDataById,
196 }).catch(noop)
197 }
198 }
199β
200 return feed
201 }
202 }))
203β
204 ...
205}
206```
207β
208[//]: # 'ExampleConditionally2'
209[//]: # 'Router'
210β
211## Router Integration
212β
213Because 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.
214β
215In 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).
216β
217For 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 Solid Query example](https://tanstack.com/router/latest/docs/framework/solid/examples/basic-solid-query-file-based) over in the [TanStack Router docs](https://tanstack.com/router/latest/docs).
218β
219When 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.
220β
221Note 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`).
222β
223```tsx
224const queryClient = new QueryClient()
225const routerContext = new RouterContext()
226const rootRoute = routerContext.createRootRoute({
227 component: () => { ... }
228})
229β
230const articleRoute = new Route({
231 getParentRoute: () => rootRoute,
232 path: 'article',
233 beforeLoad: () => {
234 return {
235 articleQueryOptions: { queryKey: ['article'], queryFn: fetchArticle },
236 commentsQueryOptions: { queryKey: ['comments'], queryFn: fetchComments },
237 }
238 },
239 loader: async ({
240 context: { queryClient },
241 routeContext: { articleQueryOptions, commentsQueryOptions },
242 }) => {
243 // Fetch comments asap, but don't block or throw errors
244 void queryClient.query(commentsQueryOptions).catch(noop)
245β
246 // Don't render the route at all until article has been fetched
247 // As this is critical data we want the error component to trigger
248 // as soon as possible if something goes wrong
249 await queryClient.query({
250 ...articleQueryOptions,
251 // If we have the article loaded already, we don't want to block on
252 // an extra prefetch; fallback on the default useQuery behavior to
253 // keep the data fresh
254 staleTime: 'static'
255 })
256 },
257 component: ({ useRouteContext }) => {
258 const { articleQueryOptions, commentsQueryOptions } = useRouteContext()
259 const articleQuery = useQuery(() => articleQueryOptions)
260 const commentsQuery = useQuery(() => commentsQueryOptions)
261β
262 return (
263 ...
264 )
265 },
266 errorComponent: () => 'Oh crap!',
267})
268```
269β
270Integration with other routers is also possible.
271β
272[//]: # 'Router'