Dependent Queries

· abundance's blog


useQuery dependent Query #

Dependent (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:

 1// Get the user
 2const { data: user } = useQuery({
 3  queryKey: ['user', email],
 4  queryFn: getUserByEmail,
 5})
 6
 7const userId = user?.id
 8
 9// Then get the user's projects
10const {
11  status,
12  fetchStatus,
13  data: projects,
14} = useQuery({
15  queryKey: ['projects', userId],
16  queryFn: getProjectsByUser,
17  // The query will not execute until the userId exists
18  enabled: !!userId,
19})

The projects query will start in:

1status: 'pending'
2isPending: true
3fetchStatus: 'idle'

As soon as the user is available, the projects query will be enabled and will then transition to:

1status: 'pending'
2isPending: true
3fetchStatus: 'fetching'

Once we have the projects, it will go to:

1status: 'success'
2isPending: false
3fetchStatus: 'idle'

useQueries dependent Query #

Dynamic parallel query - useQueries can depend on a previous query also, here's how to achieve this:

 1// Get the users ids
 2const { data: userIds } = useQuery({
 3  queryKey: ['users'],
 4  queryFn: getUsersData,
 5  select: (users) => users.map((user) => user.id),
 6})
 7
 8// Then get the users messages
 9const usersMessages = useQueries({
10  queries: userIds
11    ? userIds.map((id) => {
12        return {
13          queryKey: ['messages', id],
14          queryFn: () => getMessagesByUsers(id),
15        }
16      })
17    : [], // if users is undefined, an empty array will be returned
18})

Note that useQueries return an array of query results

A note about performance #

Dependent queries by definition constitutes a form of request waterfall, 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.

In the example above, instead of first fetching getUserByEmail to be able to getProjectsByUser, introducing a new getProjectsByUserEmail query would flatten the waterfall.