DEV Community

Cover image for How To Use Axios in an Optimized and Scalable Way With React
Nilanth
Nilanth

Posted on • Edited on • Originally published at betterprogramming.pub

How To Use Axios in an Optimized and Scalable Way With React

We can see how to use Axios in an optimized and scalable way in a React app.

When you are building an API-based React app, an HTTP client is the core service that needs to be added to the architecture. There are many HTTP client libraries for React. When deciding which to choose, Axios might be the first choice of most developers.

Axios is an HTTP client library with many advantage features. It can be used in browsers and Node.js. In this article, we will see how to utilize all the advanced Axios features in a scalable and optimized way.

Axios Instance

Creating an Axios instance is more important for a large-scale app, as all the base configuration lies in a single file. A change in the base config can be done easily in a single file and will be reflected anywhere the Axios instance is used. Check out the below code snippet

Based on the above code, we have configured all the base setup using default config, which will be applied to every request which uses the axiosClient instance, as shown in the below request.

Axios Verbs

We can group the Axios HTTP verbs, like GET, POST, DELETE, and PATCH, in the base config file, as below.

Now we can import the custom functions directly wherever we need to make an API request, as in the below code.

Timeout

The Axios timeout option allows setting the request timeout in milliseconds. It is easy to configure timeout in Axios. It can be defined in the base config itself, as we saw before.

timeout: 2000 // Request will be timeout after 2 seconds.
Enter fullscreen mode Exit fullscreen mode

Intercept Request

Using a request intercept, you can write or execute before it is sent. Check out the below code snippet.

Here we have added the contentType header before the request is made. Request interceptors are asynchronous by default, which might cause some delay in Axios request execution. To avoid this, we have used synchronous: true.

Intercept Response

Using Request intercept you can write or execute before the response reaches then. Response interceptors can be used to log out the user on token expiry (401 status) or you can refresh the token and make the failed request again to make the user stay on the same page, for good UX.

Upload Progress

You can track upload progress in Axios very easily using the onUploadProgress option. onUploadProgress allows handling of progress events for uploads. This can be used to show the upload percentage live to the user, to acknowledge to them the upload is in progress. Check out the below code.

Resources

Axios GitHub repository

Conclusion

Axios is a great HTTP client package for React and its community. I hope you have found this useful. Thank you for reading.

Need to learn more? Feel free to connect on Twitter.

You can support me by buying me a coffee ☕

eBook

Debugging ReactJS Issues with ChatGPT: 50 Essential Tips and Examples

ReactJS Optimization Techniques and Development Resources

More Blogs

  1. Redux Toolkit - The Standard Way to Write Redux
  2. 5 Packages to Optimize and Speed Up Your React App During Development
  3. 15 Custom Hooks to Make your React Component Lightweight
  4. 10 Ways to Host Your React App For Free
  5. React 18 Alpha: A Quick Overview
  6. Redux Auth Starter: A Zero Config CRA Template

Top comments (14)

Collapse
 
leandro_nnz profile image
Leandro Nuñez

This is truly useful. Thanks a lot.

Collapse
 
alexstaroselsky profile image
Info Comment hidden by post author - thread only accessible via permalink
Alexander Staroselsky • Edited

What is the need for then(response => response) on each method? Did you intend to extract data from the response so the consumer doesn't have to grab data each time? Such as return axiosClient.get(/${URL}).then(response => response.data);? Otherwise it could be removed to shorten those wrapper/helper methods.

Collapse
 
nilanth profile image
Nilanth

To access the response like below

import { getRequest } from 'axiosClient';

async function fetchUser() {
try {
  const user = await getRequest('users');
  console.log(user.data);
} catch(error) {
   //Log errors
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
alexstaroselsky profile image
Alexander Staroselsky

What happens when you remove .then(response => response) from getRequest(URL). Does it change how const user = await getRequest('users'); works at all?

Collapse
 
nazareth profile image
َ

So good 🙏

Collapse
 
kayodeadechinan profile image
Kayode Adechinan

super useful, thanks

Collapse
 
dualyticalchemy profile image
⚫️ nothingness negates itself

sweet thank you

Collapse
 
tadjerounimohamedadel profile image
Adel Mohamed Tadjerouni

Awesome

Collapse
 
solsen_tl profile image
Steven Olsen

I recommend using fetch everywhere, as axios can become bundle bloat for UIs. You just don't need it, really.

Collapse
 
sajidali2444 profile image
Sajid Ali

exactly you are correct, but how we can use interceptor in fetch ?
personally I like to use fetch

Collapse
 
nurfitrapujo profile image
Nurfitra Pujo Santiko

Awesome

Collapse
 
hussein_rk profile image
HUSSEIN RAGAB🇪🇬

Great article 👏👏

Collapse
 
h3li0 profile image
Helio da Silva Jr.

Amazing article. Super useful. Thank you ! ;-)

Some comments have been hidden by the post's author - find out more