Getting Started With useQuery (React Query)

What is React Query? React Query is a library that gives ReactJS the state management ability for any kind of asynchronous data. According to their official documentation,

React Query is often described as the missing data-fetching library for React, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your React applications a breeze.

React Query provides us custom hooks like “useQuery” to fetch data. Under the hood, these hooks manage lots of things such as caching data after the initial fetch, re-fetching data in the background, etc.

Image for post
Image for post
Source: https://react-query.tanstack.com/

In this article, I’m going to show you how to fetch data using useQuery hook. For that, I’m using JSON placeholder as an API endpoint to fetch data.

I’m starting with creating a new React JS project using create-react-app and install react-query,

npm i --save react-query

Then I clean the App.js and write the fetchUsers function to fetch data from the API. The function looks something like this. I’m using fetch(). But we can Axios or other methods as well.

const fetchUsers = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
return res.json();
};

Now import the useQuery from react-query.

import { useQuery } from "react-query";

And now we can use “useQuery” hook to manage the data fetching as below,

const response = useQuery("users", fetchUsers);

useQuery hook requires two arguments first one is a key for this query. I’m using String “users” for that. Also, we can put an array as the first argument. If an array is passed, each item will be serialized into a stable query key. The second one is a function to fetch the data. I put fetchUsers async function I created earlier. Also, we can pass an object as the third argument for different options and it is optional.

Now the response return from useQuery is really important. It has the following properties.

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

“data” is the actual data we fetched. “status” will be “loading”, “error”, “success” or “idle” according to the response. And all these properties have different uses. Refer the official documentation for more information about useQuery hook.

For my example, I’m going to use only the “data” and “status” properties. So I destruct the useQuery response as below,

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

Now we can use data to display them in the browser. Here is the complete code,

import React from "react";
import './app.css';
import { useQuery } from "react-query";

What I have done here is, check the status and display the data. This is a simple explanation of how we can use React Query useQuery hook. There are many other hooks as well.

Most of the time I used Redux or Context API for the state management in React JS projects. Now I think React Query is more powerful and will be more popular among the community and I recommend all the React developers, just try it.

Happy Coding Folks 👽

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Osusara Kammalawatta

Written by

Undergraduate in Information Systems at SUSL. I’m a developer, a designer and a content creator.

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Osusara Kammalawatta

Written by

Undergraduate in Information Systems at SUSL. I’m a developer, a designer and a content creator.

The Startup

Medium's largest active publication, followed by +773K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store