Getting Started With UseQuery in React Query

React Query provides custom hooks like useQuery to fetch data. Learn how to leverage the useQuery hook using a JSON placeholder as an API endpoint.

A person holding a magnifying glass over the word "react".
Image: Shutterstock / Built In
Brand Studio Logo
UPDATED BY
Brennan Whitfield | May 24, 2024

React Query, or TanStack Query, is a library that gives React JS the state management ability for any kind of asynchronous data. According to its official documentation, “React Query is often described as the missing data-fetching library for web applications, but in more technical terms, it makes fetching, caching, synchronizing and updating server state in your web applications a breeze.”

useQuery is a custom hook within React Query used to fetch data in a React application. Under the hood, these hooks manage lots of things such as caching data after the initial fetch, re-fetching data in the background, etc.

What Is a UseQuery?

UseQuery is a custom hook within ReactQuery that’s used to fetch data. It requires two hooks: a key, such as the string “users,” and a function to fetch the data like “fetchUsers.” 

In this article, I’m going to show you how to fetch data using the useQuery hook. To do so, I’ll be using a JSON placeholder as an API endpoint to fetch data.

 

Start a New React JS Project

Let’s start with creating a new React JS project using Create React App and install the react-query:

npm i --save react-query

Then, we’ll clean the App.js and write the fetchUsers function to fetch data from the API. I’m using fetch(), but we can use 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";

More on Software Engineering: Starting Out in Software Engineering? Don’t Bother Learning React JS.

 

How to Fetch Data With UseQuery 

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

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

A useQuery hook requires two arguments. The first one is a key for the query. I’m using the string “users” for that. We can also 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 the fetchUsers asynchronous function I created earlier. We can also pass an object as the third argument for different options, but that’s optional.

The response useQuery returns is really important. It contains the following properties.

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

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

For example, let’s use only the data and status properties. So we’ll deconstruct the useQuery response:

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";
const fetchUsers = async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  return res.json();
};
const App = () => {
  const { data, status } = useQuery("users", fetchUsers);
  return (
    <div className="App">
      {status === "error" && <p>Error fetching data</p>}
      {status === "loading" && <p>Fetching data...</p>}
      {status === "success" && (
        <div>
          {data.map((user) => (
            <p key={user.id}>{user.name}</p>
          ))}
        </div>
      )}
    </div>
  );
};
export default App;

What we’ve done here is checked the status and displayed the data. This is a simple explanation of how we can use the React Query useQuery hook. There are many other hooks as well.

A tutorial on how the useQuery hook works in React Query. | Video: The Net Ninja

More on Software Engineering: JSON vs. YAML: A Dive Into 2 Popular Data Serialization Languages

 

Advantages of UseQuery in React Query

I used to use Redux or Context API for the state management in a React JS project. But React Query is more powerful and popular among the developer community. I recommend all React developers to try it.

 

Frequently Asked Questions

UseQuery is a hook, or function, from the React Query library. It’s used to fetch and manage data, meaning it can handle API requests and state management for React applications.

React Query is a JavaScript library meant to simplify data fetching, caching and synchronizing in React applications. UseQuery is a hook included in the React Query library.

Explore Job Matches.