~2 min read • Updated Oct 24, 2025
Introduction
In earlier versions of our React application, we used the fetch API to retrieve data from external sources. However, fetch may not be supported in older browsers or headless testing environments. To address this, we can use Axios, a stable and widely adopted third-party library for making HTTP requests.
Installing and Using Axios
First, install Axios via npm:
npm install axiosThen import it into your App.jsx file:
import axios from 'axios';Replace fetch with axios.get() in your data-fetching function:
const handleFetchStories = React.useCallback(() => {
dispatchStories({ type: 'STORIES_FETCH_INIT' });
axios
.get(url)
.then((result) => {
dispatchStories({
type: 'STORIES_FETCH_SUCCESS',
payload: result.data.hits,
});
})
.catch(() =>
dispatchStories({ type: 'STORIES_FETCH_FAILURE' })
);
}, [url]);Refactoring with Async/Await
To improve readability, refactor the function using async/await:
const handleFetchStories = React.useCallback(async () => {
dispatchStories({ type: 'STORIES_FETCH_INIT' });
try {
const result = await axios.get(url);
dispatchStories({
type: 'STORIES_FETCH_SUCCESS',
payload: result.data.hits,
});
} catch {
dispatchStories({ type: 'STORIES_FETCH_FAILURE' });
}
}, [url]);Using async/await makes the code easier to follow and avoids deeply nested then chains. The try/catch block handles errors gracefully.
Benefits of Axios and Async/Await
- Better compatibility with older browsers and testing environments
- No need to manually convert responses to JSON
- Cleaner and more readable asynchronous logic
- Support for interceptors and advanced configuration
Conclusion
Using third-party libraries like Axios in React improves stability and scalability. Combined with async/await, your data-fetching logic becomes more readable and maintainable. These techniques are essential for building robust, real-world React applications.
Written & researched by Dr. Shahin Siami