React APIs
Learn how React applications request and display server data with Fetch and Axios.
Working with APIs (Fetch & Axios)
Modern web applications rarely work with static data. Instead, they receive information from servers through APIs, or Application Programming Interfaces. For example, a weather app loads weather data, an online shopping website displays products, and a social media platform shows posts from a server.
In React, you can communicate with APIs using two popular methods:
- Fetch API
- Axios
Both methods allow your application to request data from a server and display it on the screen.
What is an API?
An API, or Application Programming Interface, is a bridge that allows two applications to communicate with each other.
Instead of storing all the data inside your React application, you request it from a server using an API.
Why Do We Use APIs?
APIs allow applications to:
- Display products
- Show weather information
- Load blog posts
- Display user profiles
- Process payments
- Authenticate users
- Save and update information
Without APIs, modern web applications would not be able to display live or dynamic data.
What is the Fetch API?
The Fetch API is a built-in JavaScript feature used to request data from servers. Since it is built into modern browsers, no additional installation is required.
Fetch Example
import { useEffect } from "react";
function App() {
useEffect(() => {
fetch("https://example.com/api/products")
.then(response => response.json())
.then(data => console.log(data));
}, []);
return <h1>Loading Products...</h1>;
}Explanation
- fetch() sends a request to the server.
- The server returns a response.
- response.json() converts the response into JavaScript data.
- The data is then available for use in your application.
Using Async/Await with Fetch
Modern JavaScript often uses async and await to make asynchronous code easier to read.
useEffect(() => {
async function loadData() {
const response = await fetch(
"https://example.com/api/products"
);
const data = await response.json();
console.log(data);
}
loadData();
}, []);This version produces the same result but is often easier to understand.
What is Axios?
Axios is a popular JavaScript library used to make HTTP requests. Unlike Fetch, Axios must be installed before you can use it.
Install Axios
npm install axiosAxios Example
import axios from "axios";
import { useEffect } from "react";
function App() {
useEffect(() => {
axios
.get("https://example.com/api/products")
.then(response => {
console.log(response.data);
});
}, []);
return <h1>Loading Products...</h1>;
}Explanation
- axios.get() sends a request.
- The returned data is available through response.data.
- Axios automatically converts JSON responses into JavaScript objects.
Fetch vs Axios
Both Fetch and Axios are widely used, but they have some differences.
Feature Fetch Axios Built into browser Yes No Installation required No Yes Automatic JSON conversion No Yes Simpler syntax Moderate Yes Error handling Basic Better
Both options are excellent choices, and many developers learn both.
Displaying API Data
Once data is received from an API, React usually stores it in state and displays it using the map() method.
{
products.map(product => (
<div key={product.id}>
<h2>{product.name}</h2>
<p>₹{product.price}</p>
</div>
));
}This allows React to display multiple products dynamically instead of writing each one manually.
Handling Errors
Sometimes an API request may fail because of:
- No internet connection
- Server problems
- Invalid URL
- Permission issues
Basic Fetch error handling:
fetch("https://example.com/api")
.catch(error => {
console.log("Error:", error);
});Displaying friendly error messages helps users understand what went wrong instead of seeing a blank page.
Best Practices
When working with APIs:
- Use useEffect to load data after a component renders.
- Store API data using useState.
- Handle loading and error states.
- Avoid making unnecessary API requests.
- Keep API logic organized and readable.
- Validate the received data before displaying it.
These practices improve both performance and user experience.