React Query: Fetch data magically

Burak Erdem
4 min readJun 13, 2022

--

If you’re in the world of React, or the sister framework React Native, you probably come across of React Query, a library for data fetching conveniently and easily in your project. Having a good reputation on NPM and GitHub, this library grew fast over the years and became an essential tool belt for React developers who are dealing APIs and data fetching in their projects.

JSONs everywhere…

So whenever you’re deep into API calls and find yourself doing repetitive tasks such as setting states for incoming data, display & dismiss loading indicators, handle errors etc. you can easily use React Query for all this hassle.

On top of that, the library does the hard work that you likely unwilling to do it: Caching! This is especially where React Query shines, giving you flexibility of how and when to cache data. It has also some other powerful features like refetching, interval based fetching, preflight and so on…

Before we continue with installation, it’s worth to mention at this point that React Query has 2 main concepts as;

  • Querying — Fetching the data
  • Mutating — Creating, updating or deleting the data

Most of the time, I find myself utilizing query functions/hooks and getting the data instead of setting or deleting. Thus, I will only cover data query as most of the features are meant to do it elegantly.

OK cool! So how can I use it?
First and obvious step is to install library either with yarn or npm. React-query is pure written in JavaScript so we don’t need to install any native module.

yarn add react-query
npm install react-query --save

Then, we need to wrap up our main component with QueryClientProvider to make it available to all descendant components. QueryClientProvider has clientproperty which takes a QueryClient to manage the queries within the app.

Now we wrapped our app, we can start using library right away. To fetch data simply use useQuery hook as below:

const [isLoading, data, error] = useQuery('key', () => axios.get('path/to/api/or/something'))

So what’s going on here? Let’s dissect;

Our useQuery hook takes 2 parameters as key and fetching function. That’s right, React Query doesn’t have built-in fetching mechanism, we need to provide it explicitly. The key on the other hand is necessary for caching. So basically every time we fetch data with the same key React Query will bring it from cache except for the first time. You can quickly realize that you can use this behaviour as an alternative for Redux. If your app relies too much on API data and you occasionally find yourself using this data through the entire app, you can feel free to use React Query this way.

OK so useQuery returns us bunch of variables. You can get the complete list in https://react-query.tanstack.com/reference/useQuery but we will use frequently isLoading, data and error. The variables are pretty much self explanatory but here’s a quick explanation

  • isLoading: Loading state of the query. You can use this to compose some sort of preloader for your components. So you don’t need a separate state for loading anymore.
  • data: The data itself. The data may change actually depending of what you use for fetching. In this example for instance, since we’re using axios we can get the actual data by typing data.data
  • error: The case when an error happens you get this object containing a response for the error. Again, in this example for axios you’ll get the actual error data by error.data

Let’s all see in action:

Here we fetch the data with showing a preloading ahead and if we bump into an error we’re also showing it. The key part plays an essential role in this scenario, because React Query caches the response of this request, which means whenever we run it again we will have the same response, hence the same data. If your data is frequently changing, you can also change staleTime property to Infinity to make the data would never been stale and get it fresh every time.

Another feature is that useQuery takes enabledproperty which executes the query only if the specified condition satisfied. This is particularly useful when your query depends to other variables or data. Here’s a quick example:

You can see here that our cities are dependent to the selected country, thus useQuery that fetching the cities is only triggered when a countryId is set. You can also observe that for multiple useQueries to differentiate hook variables you can use constant aliasing — data: citiesData in this example.

Conclusion

This article is just made to get you going with React Query to facilitate your API requests and data usage in your website or app. The library includes so much more than I covered here so you can check their beautiful documentation along with examples.

I love this library so much so I will demonstrate more detailed usage of it in my upcoming articles. Until then;

Happy coding!

--

--

Burak Erdem

A technology enthusiast and a senior developer that makes things actually work