Using Reacts “useQuery” Hook To Fetch Data

Johnnie Gonzalez
3 min readMar 23, 2021

--

Photo by K. Mitch Hodge on Unsplash

First lets start with what is React-Query? It is a React library that handles state management by providing some hooks for updating, fetching and caching asynchronous data in React. With React you have to be making some kind of API call either from a third party API or your applications backend. When a state changes the user interface does as well, which can lead to multiple API calls over and over again. Upon my research I come to find that API calls can be expensive taking about half a second to get the data back. Making excessive API calls comes with a price and only increments with every call.

That’s where React-Query comes in to save the day! Making an API call using React-Query it will cache the data the first time and serve the cache data in a subsequence API call, which I found to be quite interesting! Doing so will give a better user experience as well as improved app performance!

Here we will be going over an example of how to implement the “useQuery” hook starting with installing this dependency “Axios”.

Now that we have Axios installed here is an example of a React.js file. It uses React-Query to import the “useQuery” hook, as well as Axios, so we can fetch the data that we need.

We start with all of the necessary imports from “react-query” and “axios”. To follow is a asynchronous fetch function to “GET” the specified data from the url using Axios. If you haven’t read the documentation it also handles automatic JSON data transformation decreasing the amount of code needed. Next it returns “result.data” in JSON format and ready to use!

From there I created a functional component named “Dogs” and created a useQuery hook that takes in its own values “isLoading”, “error” and “data”. The names for them are pretty obvious as to what the correct action will be taken depending on if the API call went well or not. Within the “useQuery” there are two attributes. Where it says “dogs” it can literally be any name you want. The second is the function calling the fetch “fetchDogs”. Using the boolean “if” statements if any are “truthy”. When all is said and done you can configure how you want your data to be displayed as per example above. Just to give a little more insight on the value “data” in the useQuery hook.

--

--

Johnnie Gonzalez

Software Engineering creative with background in architectural design. Love for sustainable design and tech!