Basic Dependent Query
Use theenabled option to control when a query runs:
The
enabled option accepts a boolean or a function that returns a boolean. When false, the query will not execute and will stay in an idle state.Enabled Option Types
Theenabled option can be a boolean or a function:
Multiple Dependencies
Chain multiple dependent queries:1
First query loads
The user query runs immediately when
userId is available.2
Second query waits
The company query waits until
user.companyId is available.3
Third query waits
The projects query waits until
company.id is available.Handling Loading States
Show appropriate loading states for dependent queries:Conditional Queries
Enable queries based on user actions or application state:This pattern is useful for lazy-loading data that’s not immediately needed, reducing initial load time and server load.
Query Function with Enabled
Ensure the query function can safely execute when enabled:Refetching Dependent Queries
Manually refetch dependent queries when needed:Using with Dynamic Keys
Include all dependencies in the query key for proper caching:Initial Data from Parent Query
Optimize by using data from a parent query as initial data:Using
initialData from a parent query provides instant UI updates while still fetching fresh data in the background.Dependent Mutations
Wait for a query before running a mutation:Alternative: skipToken
UseskipToken to skip queries in a type-safe way: