Introduction
Modern web applications often rely on APIs to retrieve and display dynamic data. In React, the most common way to fetch data from an API is by using the useEffect hook along with useState. The useEffect hook allows us to perform side effects such as API calls when a component loads.
In this article, we will learn how to integrate a GET API in React and display the retrieved data in the UI using a simple example.
Prerequisites
Before starting, make sure you have the following:
Basic knowledge of React
Node.js and npm installed
A React project created using create-react-app
A running backend API endpoint
Example API used in this guide: http://localhost:5288/api/Employee
This API returns a list of employees.
Step 1: Create a React Component
First, create a component that will fetch and display employee data.
import React from "react";
function Employee() {
return (
<div>
<h1>Employee List</h1>
</div>
);
}
export default Employee;
This component will later be updated to call the API and display data.
Step 2: Import React Hooks
To manage data and perform API calls, we need to import two React hooks:
import React, { useState, useEffect } from "react";
Step 3: Create State to Store API Data
We will create a state variable to store the employee data returned from the API.
const [employees, setEmployees] = useState([]);
Here:
employees stores the data
setEmployees updates the state
[] indicates the initial value is an empty array
Step 4: Call the API Using useEffect
The useEffect hook is used to call the API when the component loads.
useEffect(() => {
fetch("http://localhost:5288/api/Employee")
.then(response => response.json())
.then(data => setEmployees(data))
.catch(error => console.log(error));
}, []);
Explanation:
fetch() sends a request to the API
response.json() converts the response into JSON
setEmployees(data) saves the data into the state
[] ensures the API call runs only once when the component mounts
Step 5: Display Data Using map()
After storing the API data in state, we can display it using the map() function.
employees.map((emp) => (
<div key={emp.id}>
<p>Employee Name: {emp.name}</p>
<p>Department: {emp.branch}</p>
</div>
))
The map() method loops through the array and renders each employee's details.
Step 6: Complete React Component
Below is the complete React component that fetches and displays employee data.
import React, { useEffect, useState } from "react";
function Employee() {
const [employees, setEmployees] = useState([]);
useEffect(() => {
fetch("http://localhost:5288/api/Employee")
.then(response => response.json())
.then(data => setEmployees(data))
.catch(error => console.log(error));
}, []);
return (
<div>
<h1>Employee List</h1>
{employees.map((emp) => (
<div key={emp.id} style={{border:"1px solid black",margin:"10px",padding:"10px"}}>
<p>Employee Name: {emp.name}</p>
<p>Department: {emp.branch}</p>
</div>
))}
</div>
);
}
export default Employee;
Output
When the component loads:
The React component renders.
useEffect triggers the API call.
Data is fetched from the API.
The employee list is displayed in the UI.
Example output:
Employee Name: Rakesh
Department: Dev
Employee Name: Ramesh
Department: Dev
Employee Name: Ravan
Department: Dev
Common Issues and Fixes
CORS Error
If you see a CORS error, ensure your backend API allows requests from the React application.
Example configuration in a .NET API:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReactApp",
policy =>
{
policy.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Best Practices
When integrating APIs in React:
Always use unique keys when rendering lists
Handle errors using .catch()
Use loading states for better user experience
Separate API logic into service files for larger projects
Conclusion
Integrating APIs in React is a fundamental skill for building dynamic applications. By combining useEffect for lifecycle management and useState for state management, developers can efficiently fetch and render data from external services.
In this guide, we learned how to:
Call a GET API using fetch
Use useEffect to trigger API calls
Store data using useState
Display API data using map()