Dependent Queries
Model-written
methodresultanalysis
useQuery dependent Query
Use enabled to delay a query until its dependency is ready
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: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:Dependent queries use the enabled option to wait for previous queries This ensures a query only runs once its dependency is availableDependent queries use the enabled option to wait for previous queriesenabled option
// Get the user
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: getUserByEmail,
})
const userId = user?.id
// Then get the user's projects
const {
status,
fetchStatus,
data: projects,
} = useQuery({
queryKey: ['projects', userId],
queryFn: getProjectsByUser,
// The query will not execute until the userId exists
enabled: !!userId,
})The projects query will start in:The projects query will start in:Initially, the projects query is pending with fetchStatus idle Because it is not enabled until userId exists, no fetch occursInitially, the projects query is pending with fetchStatus idleprojects query
status: 'pending'
isPending: true
fetchStatus: 'idle'As soon as the user is available, the projects query will be enabled and will then transition to:As soon as the user is available, the projects query will be enabled and will then transition to:Once user is available, projects query becomes enabled and starts fetching The enabled option turns true when userId exists, triggering the fetchOnce user is available, projects query becomes enabled and starts fetchingprojects query
status: 'pending'
isPending: true
fetchStatus: 'fetching'Once we have the projects, it will go to:Once we have the projects, it will go to:After fetching, the projects query transitions to success with idle fetchStatus The fetch completes and data is available, so status becomes successAfter fetching, the projects query transitions to success with idle fetchStatusprojects query
status: 'success'
isPending: false
fetchStatus: 'idle'useQueries dependent Query
useQueries dynamically runs parallel queries based on prior results
Dynamic parallel query - useQueries can depend on a previous query also, here's how to achieve this:Dynamic parallel query - useQueries can depend on a previous query also, here's how to achieve this:useQueries can depend on a previous query for dynamic parallel queries It maps over prior results to create individual queriesuseQueries can depend on a previous query for dynamic parallel queriesuseQueries
// Get the users ids
const { data: userIds } = useQuery({
queryKey: ['users'],
queryFn: getUsersData,
select: (users) => users.map((user) => user.id),
})
// Then get the users messages
const usersMessages = useQueries({
queries: userIds
? userIds.map((id) => {
return {
queryKey: ['messages', id],
queryFn: () => getMessagesByUsers(id),
}
})
: [], // if userIds is undefined, an empty array will be returned
})Note that useQueries return an array of query resultsNote that useQueries return an array of query resultsuseQueries returns an array of query results This array contains the result for each query provideduseQueries returns an array of query resultsuseQueries
A note about performance
Dependent queries create waterfalls; flatten them by restructuring APIs to run in parallel
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.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.Dependent queries cause request waterfalls; parallel fetching is better Serial queries take twice as long as parallel ones, especially with high latency; restructure APIs to parallelizeDependent queries cause request waterfalls; parallel fetching is betterrequest waterfalls
In the example above, instead of first fetching getUserByEmail to be able to getProjectsByUser, introducing a new getProjectsByUserEmail query would flatten the waterfall.In the example above, instead of first fetching getUserByEmail to be able to getProjectsByUser, introducing a new getProjectsByUserEmail query would flatten the waterfall.Flatten the waterfall with a getProjectsByUserEmail query instead of two queries This combines the two fetches into one, avoiding the serial dependencyFlatten the waterfall with a getProjectsByUserEmail query instead of two queriesgetProjectsByUserEmail