Combining the Power of React Query and Axios ️‍🔥

Let's discover the benefits of combining React Query and Axios for managing your React application.

Combining the Power of React Query and Axios ️‍🔥

You probably know or used Axios before so Let's discuss the react query first.

What is React Query?

React query is a powerful library for managing server state, Api fetching, caching and updating data from a server. It provides easy-to-use, powerful asynchronous state management, dedicated dev tools, infinite-loading APIs and caching & background updates out of the box with zero configurations.

What is Axios?

Axios is a simple promise-based HTTP client for the browser and node.js. Axios provides a simple-to-use library in a small package with a very extensible interface.

Installation

$ npm i @tanstack/react-query axios
# or
$ pnpm add @tanstack/react-query axios
# or
$ yarn add @tanstack/react-query axios

We will use the latest version as of now (React query v4 and Axios v1)

Getting Started

First, create a file apiAgent.ts for the Axios config. It helps to avoid repeating the same configuration code across multiple requests. I'll use JSON placeholder Apis in this example.

import axios from "axios";

const axiosInstance = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com",
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
  },
});

export default axiosInstance;

Here you can also add Axios interceptor to add the defaults in the request and response.


Before using the react query in the component, You need to add the query client provider to the root component and also need to create the query client. I'll provide the provider with the main component.

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>
);

Now create a component to fetch the posts

import "./App.css";
import axiosInstance from "./utils/apiAgent";
import { useQuery } from "@tanstack/react-query";

const fetchPosts = async () => {
  const { data } = await axiosInstance.get("/posts");
  return data;
};

function App() {
  const { data, isLoading, isError } = useQuery({
    queryKey: ["posts"],
    queryFn: fetchPosts,
    cacheTime: 60000, // 1 minute
  });

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (isError) {
    return <div>Error loading data</div>;
  }

  return (
    <>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Title</th>
          </tr>
        </thead>
        <tbody>
          {data.map((post: { id: number; title: string }) => (
            <tr key={post.id}>
              <td>{post.id}</td>
              <td>{post.title}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}

export default App;

In the code above, we have a function called fetchPosts that uses Axios to make an API request to fetch a list of posts. We then use the useQuery hook from React Query to manage the state of the data fetching. The useQuery hook takes two arguments: the query key and the query function. The query key is a unique identifier for the query, and the query function is the function that will be called to fetch the data.

We then check the state of the query using the isLoading and isError variables. If the data is still loading, we display a loading indicator. If there was an error loading the data, we display an error message.

If the data was loaded successfully, we display it in a table.

Caching

One of the key features of React Query is caching. React Query automatically caches the data fetched by a query and provides a way to manage the cache. The cacheTime property specifies how long the data should be cached in milliseconds. In this example, we set the cache time to 1 minute. With caching enabled, React Query will automatically fetch the data from the cache if it has already been fetched and the cache time has not expired. This can greatly improve the performance of our application by reducing the number of API requests that need to be made.

Preview


Mutations - In addition to fetching data, React Query also provides a way to manage mutations, which are operations that modify data on the server. Let's add an example of a mutation to our component.

First, create an Axios function createPost that will send the post data to the server and use the useMutation react query hook to handle the state

const createPost = async (post: {
  title: string;
  body: string;
  userId: number;
}) => {
  const { data } = await axiosInstance.post("/posts", post);
  return data;
};

const { isLoading: formLoading, mutate } = useMutation({
  mutationFn: createPost,
});

Now I'll create the form to accept the user input and a function handleCreatePost to mutate the createPost on submitting the form.

 const handleCreatePost = (post: {
    title: string;
    body: string;
    userId: number;
  }) => {
    mutate(post);
  };

// HTML
<form
        style={{
          display: "flex",
          flexDirection: "column",
          width: "50%",
          margin: "50px auto",
        }}
        onSubmit={(e) => {
          e.preventDefault();
          handleCreatePost({ title, body, userId: 1 });
          setTitle("");
          setBody("");
        }}
      >
        <label>
          Title:
          <input
            type="text"
            name="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
          />
        </label>
        <label>
          Body:
          <textarea
            name="body"
            value={body}
            onChange={(e) => setBody(e.target.value)}
            required
          />
        </label>
        <button type="submit" disabled={formLoading}>
          {formLoading ? "Creating..." : "Create Post"}
        </button>
      </form>

React Query and Axios are powerful tools for managing API requests and data in React applications. React Query simplifies the process of fetching and caching data, while Axios provides a flexible and easy-to-use interface for making HTTP requests.

In this blog post, we've shown an example of how to use React Query and Axios together to fetch and display data from an API, as well as how to handle mutations. By combining these two libraries, we can create efficient and responsive applications that provide a seamless user experience.

If you're working on a React project that involves API requests, we highly recommend giving React Query and Axios a try. They can help streamline your development process and make it easier to manage complex data flows.

Project Github Link - https://github.com/baljeetjangra/react-query-and-axios

Did you find this article valuable?

Support Baljeet Jangra by becoming a sponsor. Any amount is appreciated!