API Integration – Fetch API in React
Introduction
Modern React applications often need to communicate with a backend server to fetch or send data. This data may include user information, products, posts, or dashboard statistics. The Fetch API is a built-in JavaScript feature that allows React applications to make HTTP requests to external APIs.
Understanding how to use the Fetch API correctly is essential for building data-driven React applications.
What is an API?
An API (Application Programming Interface) allows two applications to communicate with each other.
In React:
- Frontend sends a request to an API
- Backend responds with data (usually JSON)
- React displays the data in the UI
What is Fetch API?
Fetch API is a modern, promise-based JavaScript API used to make HTTP requests such as:
- GET
- POST
- PUT
- DELETE
It is supported by all modern browsers and does not require any external library.
Why Use Fetch API in React?
Fetch API helps to:
- Retrieve data from backend servers
- Send form data to APIs
- Integrate third-party services
- Build dynamic and interactive UIs
Basic Syntax of Fetch API
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
Fetch returns a Promise, which resolves to a response object.
Making a GET Request in React
Example: Fetching Data on Component Load
import { useEffect, useState } from "react";
function UsersList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => setUsers(data))
.catch((error) => console.error(error));
}, []);
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default UsersList;
Explanation:
- useEffect runs when component loads
- fetch retrieves data
- State is updated with API response
Making a POST Request in React
Example: Sending Data to API
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "React Fetch API",
body: "Learning API integration",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
Using Async and Await with Fetch
Async and await make code more readable.
const fetchUsers = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
setUsers(data);
} catch (error) {
console.error(error);
}
};
Handling Loading State
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => {
setUsers(data);
setLoading(false);
});
}, []);
Display loading indicator while data is fetched.
Handling Errors Properly
if (!response.ok) {
throw new Error("API request failed");
}
Always handle:
- Network errors
- Server errors
- Invalid responses
Fetch API with useEffect Best Practices
- Call API inside useEffect
- Add dependency array carefully
- Avoid infinite loops
- Cancel requests if needed
Common HTTP Methods with Fetch
| Method | Usage |
|---|---|
| GET | Fetch data |
| POST | Send new data |
| PUT | Update data |
| DELETE | Remove data |
Fetch API vs Axios
| Feature | Fetch API | Axios |
|---|---|---|
| Built-in | Yes | No |
| JSON parsing | Manual | Automatic |
| Interceptors | No | Yes |
| Simplicity | High | Medium |
Fetch API is suitable for most beginner and intermediate use cases.
Common Mistakes in API Integration
- Forgetting to handle errors
- Not showing loading state
- Fetching data inside render
- Ignoring response.ok
- Hardcoding API URLs
Best Practices for API Integration
- Use environment variables for API URLs
- Handle loading and error states
- Separate API logic if it grows
- Avoid unnecessary API calls
- Secure sensitive data
Interview Questions and Answers – Fetch API in React
1. What is Fetch API?
Fetch API is a built-in JavaScript API for making HTTP requests.
2. How do you call an API in React?
Using fetch inside useEffect.
3. Does fetch return JSON directly?
No, it returns a Response object that must be converted.
4. How do you handle errors in fetch?
By checking response.ok and using catch.
5. What hook is commonly used for API calls?
useEffect.
6. Can fetch handle POST requests?
Yes, using method and body options.
7. Is Fetch API asynchronous?
Yes, it works with promises.
8. Why is useEffect used for API calls?
To control when the API call runs.
9. Can Fetch API cancel requests?
Yes, using AbortController.
10. Is Fetch API production-ready?
Yes, it is widely used in production applications.
Your Feedback
Help us improve by sharing your thoughts
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.
