Tillitsdone
down Scroll to discover

Best Practices for Axios HTTP Calls in React

Learn essential best practices for making HTTP calls with Axios in React applications.

Discover how to handle errors, implement interceptors, organize API calls, and improve performance.
thumbnail

Best Practices for Making HTTP Calls with Axios in React

A futuristic abstract representation of data flow network featuring flowing light streams in bright cyan and electric blue colors against a deep metallic silver background captured from a top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Making HTTP calls is a fundamental part of modern web applications, and when it comes to React development, Axios stands out as one of the most popular choices for handling these requests. Let’s dive into some best practices that will help you write cleaner, more maintainable, and more efficient code when working with Axios in your React applications.

Setting Up Axios Instance

One of the most crucial best practices is creating a centralized Axios instance. This approach helps maintain consistency across your application and makes it easier to manage common configurations.

Instead of importing Axios directly in each component, create a separate configuration file:

api/axios.config.js
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: process.env.REACT_APP_API_URL,
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
});
export default axiosInstance;

Modern architectural structure with interconnected geometric patterns featuring warm orange and golden tones reflecting sunlight photographed from a diagonal upward angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Error Handling and Interceptors

Implementing proper error handling is essential for a robust application. Axios interceptors provide a clean way to handle errors globally:

axiosInstance.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
// Handle unauthorized access
localStorage.removeItem('token');
window.location = '/login';
}
return Promise.reject(error);
}
);

Organizing API Calls

Create dedicated service files for different features or entities in your application. This separation of concerns makes your code more maintainable and reusable:

services/userService.js
import api from '../api/axios.config';
export const userService = {
getUser: (id) => api.get(`/users/${id}`),
updateUser: (id, data) => api.put(`/users/${id}`, data),
deleteUser: (id) => api.delete(`/users/${id}`)
};

Sleek cityscape vista with modern skyscrapers dominated by emerald green glass facades and bright white architectural elements shot from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Using Async/Await with Hooks

When making API calls in React components, combine Axios with React hooks for clean and efficient data fetching:

const UserProfile = ({ userId }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const fetchUser = async () => {
try {
setLoading(true);
const { data } = await userService.getUser(userId);
setUser(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchUser();
}, [userId]);
// Component render logic
};

Request Cancellation

Remember to cancel ongoing requests when a component unmounts to prevent memory leaks and unwanted state updates:

useEffect(() => {
const abortController = new AbortController();
const fetchData = async () => {
try {
const { data } = await axiosInstance.get('/endpoint', {
signal: abortController.signal
});
// Handle data
} catch (error) {
if (error.name === 'AbortError') {
// Handle abort
}
}
};
fetchData();
return () => abortController.abort();
}, []);

Cache and Request Deduplication

Implement request caching and deduplication to improve performance and reduce unnecessary network calls:

const cache = new Map();
const fetchWithCache = async (url) => {
if (cache.has(url)) {
return cache.get(url);
}
const response = await axiosInstance.get(url);
cache.set(url, response.data);
return response.data;
};

Remember to clear the cache when needed and implement cache invalidation strategies based on your application’s requirements.

Abstract technological construct featuring flowing lines and geometric shapes in bright turquoise and metallic silver colors creating a sense of movement and connectivity captured from a dramatic side angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.