Middle
How to make HTTP requests correctly in React? How is Axios better than fetch?
sobes.tech AI
Answer from AI
In React, for HTTP requests, you can use the built-in fetch or third-party libraries like Axios.
fetch is a native browser API, simple and requires no installation, but:
- It does not automatically handle JSON (you need to call response.json() manually)
- It does not support request cancellation via AbortController in all cases
- Fewer options for configuring and intercepting requests/responses
Axios is a library that:
- Automatically transforms JSON
- Supports request cancellation
- Allows configuring base URL, headers, and interceptors
- Works in both browsers and Node.js
Example of a fetch request:
fetch('/api/data')
.then(response => {
if (!response.ok) throw new Error('Network error');
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
Example with Axios:
import axios from 'axios';
axios.get('/api/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
The choice depends on the task: for simple requests, fetch is enough; for more complex ones, Axios is more convenient.