Capítulo 16 de 80

Chapter 16: Dependent Queries

Core Idea

A query that must wait for another query's result uses enabled: !!value to stay idle until its dependency is ready — but every dependent chain is a request waterfall, which doubles latency versus a backend endpoint that could answer both needs in one round trip.

Key Concepts

  • useQuery dependent chain: fetch the first query normally, derive a value from its data (e.g. user?.id), and pass enabled: !!derivedValue to the second query so it stays inert until the value exists.
  • State progression: dependent query starts pending/idle (not enabled yet) → pending/fetching (enabled, in flight) → success/idle (resolved) — mirrors the general status/fetchStatus model with the "not yet enabled" idle phase added at the start.
  • useQueries dependent chain: derive an array (e.g. of ids) from a first query via select, then map it into a useQueries list, passing [] when the source data isn't ready yet — the empty array cleanly yields an empty results array rather than needing extra guards.
  • Performance cost: dependent queries are, by definition, a request waterfall — sequential when they could sometimes be parallel. The best fix is usually a backend change (a combined endpoint) rather than a client-side workaround.

Code Examples

const { data: user } = useQuery({ queryKey: ['user', email], queryFn: getUserByEmail })
const userId = user?.id

const { data: projects } = useQuery({
  queryKey: ['projects', userId],
  queryFn: getProjectsByUser,
  enabled: !!userId, // waits for userId
})
  • What it demonstrates: the standard two-hop dependent chain — second query's enabled gates on a value derived from the first.

Key Takeaways

  1. enabled: !!derivedValue is the whole mechanism for dependent queries — no special hook is needed for the useQuery case.
  2. Every dependent chain is a waterfall; before reaching for this pattern, check whether the backend could expose a combined endpoint instead (e.g. getProjectsByUserEmail) to fetch in parallel.
  3. For a dependent list built with useQueries, pass an empty array as the fallback queries value rather than skipping the hook call — this keeps hook order stable.

Connects To

  • Performance & Request Waterfalls: the general problem this pattern is one instance of.
  • Parallel Queries: the useQueries mechanism reused here for the dependent-list case.