Open History to see the last commit
1---
2id: dependent-queries
3title: Dependent Queries
4---
5β
6## useQuery dependent Query
7β
8Dependent (or serial) queries depend on previous ones to finish before they can execute. To achieve this, it's as easy as using the `enabled` option to tell a query when it is ready to run:
9β
10[//]: # 'Example'
11β
12```tsx
13// Get the user
14const { data: user } = useQuery({
15 queryKey: ['user', email],
16 queryFn: getUserByEmail,
17})
18β
19const userId = user?.id
20β
21// Then get the user's projects
22const {
23 status,
24 fetchStatus,
25 data: projects,
26} = useQuery({
27 queryKey: ['projects', userId],
28 queryFn: getProjectsByUser,
29 // The query will not execute until the userId exists
30 enabled: !!userId,
31})
32```
33β
34[//]: # 'Example'
35β
36The `projects` query will start in:
37β
38```tsx
39status: 'pending'
40isPending: true
41fetchStatus: 'idle'
42```
43β
44As soon as the `user` is available, the `projects` query will be `enabled` and will then transition to:
45β
46```tsx
47status: 'pending'
48isPending: true
49fetchStatus: 'fetching'
50```
51β
52Once we have the projects, it will go to:
53β
54```tsx
55status: 'success'
56isPending: false
57fetchStatus: 'idle'
58```
59β
60## useQueries dependent Query
61β
62Dynamic parallel query - `useQueries` can depend on a previous query also, here's how to achieve this:
63β
64[//]: # 'Example2'
65β
66```tsx
67// Get the users ids
68const { data: userIds } = useQuery({
69 queryKey: ['users'],
70 queryFn: getUsersData,
71 select: (users) => users.map((user) => user.id),
72})
73β
74// Then get the users messages
75const usersMessages = useQueries({
76 queries: userIds
77 ? userIds.map((id) => {
78 return {
79 queryKey: ['messages', id],
80 queryFn: () => getMessagesByUsers(id),
81 }
82 })
83 : [], // if users is undefined, an empty array will be returned
84})
85```
86β
87[//]: # 'Example2'
88β
89**Note** that `useQueries` return an **array of query results**
90β
91## A note about performance
92β
93Dependent queries by definition constitutes a form of [request waterfall](./request-waterfalls.md), which hurts performance. If we pretend both queries take the same amount of time, doing them serially instead of in parallel always takes twice as much time, which is especially hurtful when it happens on a client that has high latency. If you can, it's always better to restructure the backend APIs so that both queries can be fetched in parallel, though that might not always be practically feasible.
94β
95In the example above, instead of first fetching `getUserByEmail` to be able to `getProjectsByUser`, introducing a new `getProjectsByUserEmail` query would flatten the waterfall.