Fetching data from APIs is a core skill in React development, allowing applications to interact with external data sources such as servers and databases.
React itself does not include built-in tools for API calls, so developers use JavaScript methods like fetch or libraries like Axios.
What is an API?
An API (Application Programming Interface) allows different software systems to communicate with each other.
In web development, APIs are commonly used to send and receive data between frontend and backend systems.
Using fetch in React
The fetch API is a built-in JavaScript method used to make HTTP requests.
It returns a promise that resolves into a response object, which can be converted into JSON.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));Fetching Data in React Components
In React, API calls are usually made inside the useEffect hook to ensure data is fetched when the component loads.
import { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://api.example.com/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return <div>{users.length} users loaded</div>;
}Understanding useEffect for API Calls
useEffect ensures that API calls are executed after the component renders.
Using an empty dependency array ensures the API call runs only once on mount.
Handling Loading State
While fetching data, it is important to show a loading state to improve user experience.
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://api.example.com/users')
.then(res => res.json())
.then(data => {
setUsers(data);
setLoading(false);
});
}, []);Error Handling
Handling errors is important when working with APIs because network requests can fail.
You can use catch() or try-catch with async/await to manage errors.
fetch('https://api.example.com/users')
.then(res => res.json())
.then(data => setUsers(data))
.catch(error => console.error('Error:', error));Using Async/Await
Async/await provides a cleaner and more readable way to handle asynchronous API calls.
useEffect(() => {
async function fetchData() {
try {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
setUsers(data);
} catch (error) {
console.error(error);
}
}
fetchData();
}, []);Displaying API Data
Once data is fetched, it can be displayed using the map function in React.
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);Real-World Usage
Fetching data from APIs is used in dashboards, social media feeds, e-commerce products, and authentication systems.
Almost every modern React application depends on API integration.
Best Practices
Always handle loading and error states for better user experience.
Keep API logic clean and consider separating it into reusable custom hooks.
Summary
Fetching data from APIs is essential for building dynamic React applications.
Mastering API calls, state management, and error handling is key for every React developer.