NashTech Blog

React Query and Axios: A complete guide using react

Table of Contents
axios react query

Introduction

React application API call management may easily become complicated, particularly as your project expands and demands effective data processing. React Query and Axios work together to simplify your API logic and cut down on boilerplate code while providing you with strong capabilities for data retrieval, caching, and error handling. Intelligent caching, background updates, and request deduplication are just a few of the capabilities that React Query offers to facilitate data management and enhance application performance. This combination, when combined with Axios’ adaptable and user-friendly API request handling, enables developers to create scalable and maintainable apps with little work. Adopting these tools guarantees a better user experience through dependable and effective data processing, in addition to streamlining development.

Why Choose React Query with Axios?

  • React Query: Handles caching, background synchronization, and data mutation.
  • Axios: A powerful HTTP client for easy and efficient API requests.
  • Seamless Integration: These two libraries work well together to build scalable and maintainable applications.

Getting Started

To build a project using React Query and Axios, follow the steps outlined below.

Installation

First, create your React project using Yarn:

yarn create react-app react-query-axios-demo --template typescript
cd react-query-axios-demo

Next, install required packages:

yarn add @tanstack/react-query axios

Also, install the React Query Devtools (optional but recommended):

yarn add @tanstack/react-query-devtools

Setting Up API Fetching

api.ts
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 10000,
});

export const fetchPosts = async () => {
  const response = await apiClient.get('/posts');
  return response.data;
};

Using React Query in a Component

Create a component to display the fetched posts:

Posts.tsx
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { fetchPosts } from './api';
import { CircularProgress, List, ListItem, ListItemText } from '@mui/material';

const Posts: React.FC = () => {
  const { data, error, isLoading } = useQuery(['posts'], fetchPosts);

  if (isLoading) return <CircularProgress />;

  if (error instanceof Error) return <p>Error: {error.message}</p>;

  return (
    <List>
      {data.map((post: { id: number; title: string }) => (
        <ListItem key={post.id}>
          <ListItemText primary={post.title} />
        </ListItem>
      ))}
    </List>
  );
};

export default Posts;

Running the Application

Start the development server:

yarn start

Visit http://localhost:3000 to see your posts displayed.

Conclusion

We showed in this blog post how to use TanStack RQ and Axios to set up a project for effective data fetching in React applications. This combination keeps the software clean and scalable while enabling developers to handle API logic with ease. Axios’ adaptability in managing HTTP requests, along with React Query’s features like caching, background updates, and request deduplication, minimise boilerplate code and expedite development. Better user experiences, a more maintainable codebase, and more seamless asynchronous activities are all guaranteed by this method. It’s revolutionary for contemporary development, regardless of the size of the project or the application. Have fun with your coding!

Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency.

Picture of anshumantnt

anshumantnt

Leave a Comment

Suggested Article

Discover more from NashTech Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading