Dependent queries in React Query allow you to execute queries that depend on the results of previous queries. This is useful when you need data from one query to make another query.
Basic Implementation
jsx
import { useQuery } from '@tanstack/react-query';
function MyComponent() {
// First query
const { data: user, isLoading: userLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId),
});
// Dependent query - only executes when user data exists
const { data: userProjects, isLoading: projectsLoading } = useQuery({
queryKey: ['projects', user?.id],
queryFn: () => fetchUserProjects(user.id),
// The important part - only enable this query when user data exists
enabled: !!user?.id,
});
if (userLoading) return <div>Loading user...</div>;
if (projectsLoading) return <div>Loading projects...</div>;
return (
<div>
<h1>{user.name}'s Projects</h1>
{userProjects?.map(project => (
<div key={project.id}>{project.name}</div>
))}
</div>
);
}
Key Points
The enabled option: This is the key to dependent queries. Set it to a boolean condition that depends on the data from the first query.
Query keys: Make sure to include the dependency in the query key (like user.id in the example) to ensure proper cache invalidation.
Loading states: Handle loading states for both queries appropriately.