Performing dependent queries in React Query (also known as dependent data fetching or conditional queries) is a highly valuable technique that enables you to execute queries sequentially and conditionally when the data of one query depends on another. This is very common in real-world applications, for instance, you might need to first retrieve a user's ID from an API and then use that ID to fetch the user's detailed information.
Usage
To implement dependent queries in React Query, you typically utilize the enabled option of the useQuery hook. This option accepts a boolean value to control whether the query runs automatically. If enabled is set to false, the query will automatically start when the condition evaluates to true.
Example
Assume we have two API endpoints:
/api/userreturns the user's ID./api/details/:userIdfetches the user's detailed information using the user ID.
We want to fetch the user's detailed information only after retrieving the user ID. Here is how to implement this logic using React Query:
jsximport { useQuery } from 'react-query'; import axios from 'axios'; function UserProfile() { // First query: fetch user ID const { data: user, isSuccess: isUserFetched } = useQuery('user', () => axios.get('/api/user').then(res => res.data) ); // Second query: dependent query for user details const { data: userDetails, isLoading, isError, error } = useQuery( 'userDetails', () => axios.get(`/api/details/${user.id}`).then(res => res.data), { // Only start this query when the first query is successful and user.id exists enabled: isUserFetched && user && user.id } ); if (isLoading) return <div>Loading user details...</div>; if (isError) return <div>An error occurred: {error.message}</div>; // Render user details return ( <div> <h1>User Details</h1> <p>Name: {userDetails.name}</p> <p>Age: {userDetails.age}</p> </div> ); }
Explanation
- First query (
useQuery('user', ...)) fetches basic user information, assuming the response includes the user ID. - Second query (
useQuery('userDetails', ...)) fetches detailed information based on the user ID. Its execution depends on the result of the first query. By using theenabledproperty, we ensure the query starts only after the user ID is retrieved.
This approach ensures data loading occurs in the required sequence while maintaining code clarity and maintainability.