Conditional Queries with React-Query

Written on 2023-06-16 by Adam Drake - 3 min read
Image of Conditional Queries with React-Query
React-Query (Tanner Query) is a great library for working with external APIs. It saves you a tonne of trouble with `useEffect` and `useState` when calling APIs and also the cache it provides really helps speed up things in your application.
It's quite an intuitive library to use once you understand it's purpose and great for doing standard things in your app when working with external APIs - like fetching data and doing some POST and PATCH requests.
However, there are many options and tweaks you can play around with and once you use React-Query in an application of any size then it really pays off getting to know some of these.

Conditional Queries

React-query is built around React hooks and because of the Rules of Hooks, one can't call hooks conditionally. So what happens if you have a situation where you want to make an API GET request based on some `id` but you don't know if that id will be available or not?
Well there is an option on the useQuery hook which can be passed which basically says - if this condition is true then make the query, if not then don't. The option in question is `enabled`. It allows you to make dependent queries.
The example they give in the docs is a great showcase for how useful this can be:
// Get the user
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: getUserByEmail,
const userId = user?.id
// Then get the user's projects
const {
data: projects,
} = useQuery({
queryKey: ['projects', userId],
queryFn: getProjectsByUser,
// The query will not execute until the userId exists
enabled: !!userId,
First there is a call to get the user data. Once this is done the `userId` can be found. On the second useQuery hook for the projects you can see there is the enabled option:
// The query will not execute until the userId exists
enabled: !!userId,
The projects hook actually starts with the following:
status: 'loading'
fetchStatus: 'idle'
So this hook will not execute without the userId being available. Once the userId becomes available it will fetch this query and upon success it will provide the required data. This is great and exactly what we wanted.


React-Query (Tanner Query) is a great tool to add to any developer's tool belt and is relatively easy to get started with. However, it is an established library and on v4 so it also has some cool additional options to help deal with more niche cases. It's well worth spending the time getting to know these options as it provides you with more flexibility when building your application.
Adam Drake AI Selfie

Written by Adam Drake

Adam Drake is a Frontend React Developer who is very passionate about the quality of the web. He lives with his wife and three children in Prague in the Czech Republic.
Adam Drakes Site © 2023