author avatar

ashwanikumarjha

Mon Dec 18 2023

In a web application, there can be scenarios where certain data needs to be fetched conditionally. For eg, in application with multiple user roles, there might be a specific role for which certain data is not needed. In such a case, we might want to avoid making unnecessary API calls to fetch that data. However, due to React's rules of hooks, we cannot directly conditionally call a hook which fetches data.

If you're using a library like react-query and if you do not want to create a wrapper component to fetch the data, react-query provides a good solution. react-query has an enabled option for its useQuery hook. We can conditionally enable or disable the query based on our needs.

const { data, isLoading } = useQuery(
 ['user', userId], 
 fetchUserData, 
 { enabled: isAuthenticated }
);

Here the useQuery is only executed if isAuthenticated is true. If isAuthenticated is false, the query is skipped.