Part 35: Data Fetching Patterns with Fetch API & Axios
Understanding how native fetch and third-party HTTP clients like axios integrate with React lifecycles—specifically dealing with component unmounting and request cancellation—is essential for bug-free applications.
1. The Native fetch Pattern with AbortController
When a user navigates away from a page while a request is in-flight, setting state on an unmounted component leads to memory leaks and race conditions. Cancel in-flight requests using AbortController:
import { useState, useEffect } from 'react';
export default function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
async function loadUser() {
try {
const response = await fetch(`https://api.example.com/users/${userId}`, {
signal: controller.signal
});
if (!response.ok) throw new Error(`HTTP Error: ${response.status}`);
const data = await response.json();
setUser(data);
} catch (err) {
if (err.name !== 'AbortError') {
setError(err.message);
}
}
}
loadUser();
// Cleanup: Abort request if userId changes or component unmounts
return () => controller.abort();
}, [userId]);
if (error) return <p>Error: {error}</p>;
if (!user) return <p>Loading user profile...</p>;
return <div><h1>{user.name}</h1><p>{user.email}</p></div>;
}
2. Axios with Global Interceptors
Axios offers automatic JSON parsing, request/response interceptors (ideal for attaching JWT Bearer tokens), and better default error handling:
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.devifyblog.com',
timeout: 10000,
});
// Attach Authorization header to every outgoing request
apiClient.interceptors.request.use((config) => {
const token = localStorage.getItem('auth_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
Key Takeaways
- Always cancel in-flight HTTP requests during
useEffectcleanup usingAbortController. - Ignore
AbortErrorin catch blocks to prevent false error notifications. - Use Axios interceptors for centralized auth tokens and error logging.
In Part 36, we will build Loading States, Skeleton Screens & Error UI!

