React Query

React Query Tutorial: Getting Started with Fetching Data and State Management with Examples

August 26, 2022
Emmanuel Uchenna
React.js

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Table of Contents
  1. Introduction
  2. What is React Query library
  3. Features of React Query
  4. Apollo Client Vs React Query Vs URQL: A Detailed Comparision
  5. Is React Query good enough?
  6. Benefits of using React Query in your React application
  7. Steps to use React Query Library to fetch data from API
  8. Getting started with your React app
    • Setup your development environment
  9. Getting started with React Query
  10. Alternatives to React Query
  11. Conclusion
  12. Further readings
  13. Video on React Query and Examples

Introduction

Building a full-stack application is incomplete until when you can exchange data between different components. Fullstack application refers to being able to carry out the CRUD operations. The most important aspect of a full-stack application is the ability to exchange data. There are different ways to do this which range from using the Fetch API, to using your custom useFetch hook, to using the Axios library, and lots more. React Query is a library that will help you carry out CRUD operations in your React Application also, helping you manage state, synchronization, caching, and error handling.

What is React Query library

React Query is a ReactJS preconfigured data management library which gives you power and control over server-side state management, fetching, and caching of data, and error handling in a simple and declarative way without affecting the global state of your application.

Server data is asynchronous – it can easily be outdated, this is because the data is not stored in your React application. This is where the Query library shines, to allow you to manipulate the asynchronous data, cache it, and also, update stale data or synchronize it.

There is absolutely no point trying to re-invent the wheel by trying to write your code that will handle caching, optimistic UI updates, and other handy features. There are a handful of libraries that provides these features out of the box. React Query is jam packed with tons of helpful features!

React Query

Features of React Query

Aside from the benefits discussed already, you should consider using this library for your next project because React Query takes care of:

  • Caching: Window focus refetching – This allows it to pre-fetch data depending on your application activity
  • Request retry: Ability to set the number of request retries in the event of errors.
  • Prefetching – It is able to pre-fetch data depending if your application needs fresh data after an update network request. It is able to update data in the background.
  • Optimistic updates – It is also able to handle complex caching so that your application is fully optimized.

Apollo Client Vs React Query Vs URQL: A Detailed Comparision

  • Apollo client is a GraphQL implementation that enables developers to manage data in their applications. The team at Apollo also made the Apollo Client, a GraphQL client that can be used in your React applications.
  • URQL is a highly customizable and versatile GraphQL client for React, Svelte, Vue, or plain JavaScript, with which you add on features like normalized caching as you grow.
  • React Query, on the other hand, is an open-source project by Tanner Linsey. As pointed out above, React Query is a pre-configured library that solves the problem of fetching, caching, and optimistic data updates in your React applications.
ComparisonReact QueryURQLApollo Client
GitHub stars29k7.418k
Ease of useVery easyEasyEasy
Platform requiredReactReact, Preact, and SvelteReact, GraphQL
Query support✅✅✅
Window Focus Refetching✅✅🛑
Customizable✅✅✅
Caching✅✅✅
Data fetching✅🛑🛑
GraphQL🛑✅✅

Is React Query good enough?

React Query is a big thing because it helps with server-state data management. This means that you no longer have to worry about keeping everything in a standard global state because most libraries were created to handle client state only and the server states are way different. React Query is good enough because this library will help you to fetchsynchronizeupdate, and cache your remote data while also reducing the amount of code you need to write by providing you two simple hooks and one utility function. With React Query, you do not need to write boilerplate codes to enable it to post with React as is the case with the other libraries.

Benefits of using React Query in your React application

  • Ease of data fetching
  • It is becoming the standard way to fetch data
  • Fun ways of fetching data
  • Highly customizable
  • Lightweight

Steps to use React Query Library to fetch data from API

Getting started with your React app

In this tutorial, you will be creating a React app using CRA.

Setup your development environment

You will scaffold a new React project. In this tutorial, I refer to my React app as react-query-tutorial. In your terminal, type the following:

1
npx create-react-app react-query-tutorial

After having created your app and all dependencies automatically installed, you will need to navigate into the project directory and run the app. For that, run the following command in your terminal:

1
cd react-query-tutorial && npm start

You should see similar output below in your terminal:

1
2
3
4
$ npm start
 
> react-query-tutorial@0.1.0 start
> react-scripts start

You should get the following in your terminal upon completion of the commands above:

1
2
3
4
5
6
7
8
9
Compiled successfully!
 
You can now view react-query-tutorial in the browser.
 
  Local:            http://localhost:3000
  On Your Network:  http://192.168.137.1:3000
 
Note that the development build is not optimized.
To create a production build, use npm run build.

If your web pack is compiled successfully then your React app will start hot reloading your development environment, and your app should be running on localhost:3000 by default.

image of React app

Getting started with React Query

  • Install official React Query and react-query-devtools
1
yarn add react-query && yarn add react-query-devtools -f

or

1
npm install react-query && npm install react-query-devtools -f
  • You installed react-query-devtools because it is difficult to debug data fetching, that is why you need to install react-query-devtools. It will help you to see and understand how React Query does data fetching. The -f flag is passed to the command to resolve any dependencies issues while installing react-query-devtools.
  • Next, you will import QueryClientProvider and QueryClient in your App.js like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// App.js
 
  import { QueryClient, QueryClientProvider } from "react-query";
  import { ReactQueryDevtools } from "react-query-devtools";
 
  const queryClient = new QueryClient({});
 
  const App = () => {
    return (
      <QueryClientProvider client={queryClient}>
       
 
        {/* The rest of your application */}
 
        <ReactQueryDevtools initialIsOpen={true} />
 
      </QueryClientProvider>
    );
  };
 
  export default App;

You initialized ReactQueryDevtools‘s initialIsOpen to true to enable the dev tools to default to being open.

  • useQuery Hook The useQuery hook handles the fetching of data. It is called whenever you need to fetch data. It accepts a unique key for the query and a function that returns a promise. The unique key is used to refetch, cache, and share your query internally.
    • Using the useQuery hook
1
const fetchedData = useQuery(key, promiseBasedFn);

The useQuery hook returns a handful of objects such as isSuccessisErrorisLoadingisFetchingdata, and error.

Enough said, let us get your hands dirty with code by walking you through actually using React Query and the useQuery hook to fetch actual data in your React Application.

coding cat

Tutorial

  • For the purpose of this tutorial, you will be using the GitHub REST API to get a list of public repositories of the Eunit99 on GitHub. You will make the request to the following endpoint https://api.github.com/users/eunit99/repos. It returns all the stored data about the user, eunit99. With this response, you can decide to render it whichever way we like in your React app.
  • You will create a component called Repositories.jsx which will display a list of user’s repositories.

Your folder structure might look like so:

folder structure
  • Next, you will make use of Axios as your promise-based function to fetch our data. Start by installing it by hitting the command npm i axios on your terminal.
  • Then inside your Repositories.jsx component, paste the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// components/Repositories.jsx
 
import React from "react";
import axios from "axios";
import { useQuery } from "react-query";
 
 
 
export default function Repositories() {
 
  const { isLoading, isError, data, error, refetch } = useQuery(["repo"], () =>
    axios
      .then((res) => res.data)
  );
 
  if (isLoading) return "Loading...";
 
  if (error) return "An error has occurred: " + error.message;
 
  console.log(data)
   
 
 
  return (
    <>
      ...
 
    </>
  )
};
  • Explanations of what is going on
    • You pass in a unique key called repo to the useQuery hook
    • The second argument to the useQuery hook is the promise-based function for fetching our data where you make use of Axios.
    • Another notable thing you did is that you make use of object destructuring to destructure your object response. You will make use of them in the next example.
  • The complete Repositories.jsx component will look like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// components/Repositories.jsx
 
import React, { Fragment } from "react";
import axios from "axios";
import { useQuery } from "react-query";
 
 
 
export default function Repositories() {
 
  const { isLoading, isError, data, error, refetch } = useQuery(["repo"], () =>
    axios
      .then((res) => res.data)
  );
 
  if (isLoading) return "Loading...";
 
  if (error) return "An error has occurred: " + error.message;
 
  console.log(data)
 
    return (
      <>
        {data.map(repo => {
          return (
            <Fragment
              key={repo.id}
            >
              <ul>
                <li>
                  <a
                    href={repo.clone_url}>
                    {repo.name}
                  </a>
                </li>
              </ul>
            </Fragment>
          )
        })}
        <button type="button" onClick={refetch}>
          Fetch again
        </button>
      </>
    );
  };

Finally, your end result will look like so: 

Alternatives to React Query

Conclusion

In this tutorial, you learned about React Query and how to use it to to handle data fetching in your React application.

You can find the complete source code of this tutorial in this repository.

Further readings

Video on React Query and Examples

If you’re looking out for cool React tools that’ll help you to write component code faster and be production ready faster than your competition, don’t forget to check out the CopyCat plugin for React!

Happy Coding!

Related Articles

  • React.js

    React useContext: The Best Way to Manage State in React

    How React useContext Helps You Imagine you're building an e-commerce website that allows users to purchase products from multiple vendors. Each vendor has its own inventory and shipping policies, and you need to keep track of all this information to…

    March 22, 2023
  • React.js

    How To Use React Styled Components in React Efficiently

    Introduction As libraries evolve and software grows bigger and more complex, the need for a better styling approach grows. Especially for styled components react. The component-driven approach to building software applications majorly influenced by modern libraries and frameworks begs for…

    July 12, 2022

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code