React JS Fetch, and Cache Data using React Query Tutorial

Last updated on: by Digamber

React Query Fetch Request example. In this tutorial, we will learn how to create a basic React App and communicate with the server to fetch and cache the data using React Query.

React is an outstanding framework. However, it also has some downfalls. React applications do not come with an opinionated way of fetching or updating data from your components; hence developers end up producing their own methods of fetching data.

This ideally means cobbling together component-based state and effect using React hooks or using more general-purpose state management libraries to store and provide asynchronous data throughout their apps.

There are tons of excellent state management libraries out there. However, they are not upto the mark when it comes to managing async or server state.

In general, managing server states are cumbersome. As soon as you put your hands on the server state, some challengers manifest automatically:

  • Data Caching
  • Getting to know when data gets old
  • Updating old data in the background
  • Updating the latest changes in the data
  • Memoizing query results with structural sharing
  • Managing memory with a waste pool of server state
  • Performance optimizations for pagination and lazy loading of data
  • Deduping multi requests for the same data through a single request

We have discussed the advantages and benefits of using React Query in React.

Now, let’s have a look at the useQuery hook:

The React Query is a server-state package that manages asynchronous operations between the server and the client. The useQuery hook is available through the react-query library.

The useQuery hook is a simple yet powerful function mainly used to implement data fetching code in contrast with React query module.

How to Use useQuery Hook to Fetch, and Cache Data in React with React Query

  • Step 1: Build React Project
  • Step 2: Install Axios & React Query
  • Step 3: Set Up Bootstrap
  • Step 4: Configure React-Query in React
  • Step 5: Create Function Component
  • Step 6: Fetch Data with useQuery Hook
  • Step 7: Update App JS Component
  • Step 8: Test App on Browser

Build React Project

Let’s start off by building a new React project with given command.

npx create-react-app react-blog-app

Immediately after the app is built, move into the app folder.

cd react-blog-app

Install Axios & React Query

In order to deal with fetch request and fetch request management install axios and react-query libraries.

npm install @tanstack/react-query axios

Set Up Bootstrap

We will use the command to install the bootstrap CSS library in our project.

npm i bootstrap

To make the bootstrap work in React at full-scale add the module CSS in src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
function App() {
  return <div></div>;
}
export default App;

Configure React-Query in React

We are going to add React-Query in a React app. You can do it by wrapping the App.js component using the QueryClientProvider and QueryClient from the react-query package.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// Create a client
const queryClient = new QueryClient();
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

It will grant us access to all the hooks from the react-query module.

Create Function Component

We now need to make the components/ folder and the Users.js file.

import React from 'react'
function Users() {
  return (
    <div>Users page</div>
  )
}
export default Users

Fetch Data with useQuery Hook

In order to manage the fetch data request state, put the following code inside the components/Users.js file.

import React from "react";
import axios from "axios";
import { useQuery } from "@tanstack/react-query";
async function fetchData() {
  const { data } = await axios.get(
    "https://jsonplaceholder.typicode.com/users"
  );
  return data;
}
function Users() {
  const { isLoading, isError, error, data } = useQuery(["users"], fetchData);
  if (isLoading) {
    return <div>Data is loading...</div>;
  }
  if (isError) {
    return <div>Error! {error.message}</div>;
  }
  return (
    <ul className="list-group">
      {data.map((res, i) => {
        return (
          <li className="list-group-item mb-3" key={i}>
            <h3>{res.username}</h3>
            <p>{res.email}</p>
          </li>
        );
      })}
    </ul>
  );
}
export default Users;

Update App JS Component

Your next move is to add the Users component to the App.js file; this will make the Users component available in our React app.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import Users from "./components/Users";
function App() {
  return (
    <div className="container mt-5">
      <h2>React Query Fetch State Management Example</h2>
      <Users />
    </div>
  );
}
export default App;

Test App on Browser

We have eventually reached at the final step of this post; Just, open the console and execute the given command.

npm start

Once the server is running, use the below url to test the app on the browser.

http://localhost:3000

React JS Fetch, and Cache Data using React Query Tutorial

Conclusion

React Query is a wonderful tool, but that doesn’t mean you should not try other options as well. Redux is also another powerful and handy option available.

That is the ultimate elixir for web developers; to make yourself proficient in managing global state, you must give a try to both React Query and Redux.

In this article, we saw how to set up React query in React application. How to use the useQuery hook to make an asynchronous call to the server to fetch the data.

Not only but also how to quite effortlessly manage the useQuery hook response containing loading, isError, error, data, and success.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.