Getting Started with useQuery of React Query

Dhrubo Dh
3 min readMar 25, 2021

React Query is a ReactJS library that provides state management ability for any kind of asynchronous data. React Query makes fetching, caching, synchronizing, and updating server states very easy.

useQuer is one of the hooks provided by React Query to fetch data. Under the hood, these hooks manage lots of other things like caching data after the initial fetch, re-fetching data in the background, etc. In this post, I will explain my first attempt and steps that I took to fetch data with useQuery hook using a demo.

First, I created a brand new React app using create react app and installed React Query.

npm i react-query

I used https://jsonplaceholder.typicode.com/ to fetch some mock data. In my App.js I cleared out the boilerplate code and wrote a fetch method that uses async-await and fetches some posts data from JSONPlaceholder.

FetchPosts function

Then, I had to import useQuery from react-query. This gives me the ability to manage fetching data using useQuery hooks and useQuery requires a key and a function that fetches and optional option objects. Similar to this:

const response = useQuery("string", fetchThat);

Here I am using a string as a key for the first argument, alternatively, I could use an array as well, If an Array is used, each item will be serialized into a stable query key. The second one is a function to fetch the data from the backend or a remote source. The response return from useQuery has the following properties:

data,
error,
failureCount,
isError,
isFetchedAfterMount,
isFetching,
isIdle,
isLoading,
isPreviousData,
isStale,
isSuccess,
refetch,
remove,
status,

I just used “data” and “status” where data is the data that has been fetched and status is the state which is: “loading”, “error”, “success” or “idle”. Using destructuring, I extracted data and status as below:

const { data, status } = useQuery("posts", fetchUsers);

Now I had the data, and was ready to display it:

This should’ve been working in the browser ut it was giving me this error in the browser:

After, reading the official docs for React Query I realized that I need to wrap the app component with a Query client. Approaching the Higher-Order Component approach this was quickly fixed like this:

Essentially what I did is instead of exporting App regularly I wrapped it with QueryClient that was provided by React Query. Now the program was working fine with browser:

This is how I got started using the useQuery and React Query. I would appreciate any comments or suggestions. Thank you for reading.

--

--