How to Fetch and Display API Data in React (Beginner to Advanced Guide)

How to Fetch and Display API Data in React

How to Fetch and Display API Data in React – In today’s web development world, almost every application depends on APIs to function. Whether it’s a social media platform loading posts, an eCommerce site displaying products, or a dashboard showing analytics — data is constantly being fetched from servers and displayed dynamically on the screen.

If you’re learning React, understanding how to fetch and display data from an API is one of the most essential skills you must master. Without API integration, your application remains static and limited. With it, your app becomes dynamic, interactive, and production-ready.

React makes this process simple and efficient using modern tools like Hooks, especially useState and useEffect. Combined with JavaScript’s built-in fetch() function or libraries like axios, you can easily request data, manage responses, handle errors, and update your UI seamlessly.

How to Fetch and Display API Data in React

Understanding APIs in Simple Terms

An API (Application Programming Interface) allows your frontend to communicate with a backend server.

For example:

  • A weather app requests temperature data.
  • A blog app requests posts from a database.
  • A shopping app requests product lists.

React itself doesn’t store backend data — it simply fetches it and displays it.

The most common API request type is:

GET → Used to retrieve data.


Setting Up Your React Project

Create a React app:

npx create-react-app react-api-demo
cd react-api-demo
npm start

Or using Vite (faster modern setup):

npm create vite@latest react-api-demo
cd react-api-demo
npm install
npm run dev

Now you’re ready to fetch data.


Important React Hooks You Need

🔹 useState

Stores data inside the component.

🔹 useEffect

Runs side effects like API calls.

Basic structure:

useEffect(() => {
// API call here
}, []);

The empty dependency array [] ensures the API runs only once when the component loads.


Method 1: Fetch Data Using fetch()

Let’s use a free public API:

https://jsonplaceholder.typicode.com/users

Complete Example:

import React, { useEffect, useState } from "react";function App() {
const [users, setUsers] = useState([]); useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => {
if (!response.ok) {
throw new Error("Network response failed");
}
return response.json();
})
.then((data) => {
setUsers(data);
})
.catch((error) => {
console.error("Error:", error);
});
}, []); return (
<div>
<h1>User List</h1>
{users.map((user) => (
<div key={user.id}>
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
))}
</div>
);
}export default App;

Adding Loading State (Very Important)

Without loading state, the screen looks empty while data loads.

Improved version:

const [loading, setLoading] = useState(true);useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => {
setUsers(data);
setLoading(false);
});
}, []);if (loading) {
return <p>Loading data...</p>;
}

Now users see feedback immediately.


Adding Error Handling (Professional Way)

Add error state:

const [error, setError] = useState(null);useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => {
if (!res.ok) throw new Error("Failed to fetch");
return res.json();
})
.then((data) => {
setUsers(data);
setLoading(false);
})
.catch((err) => {
setError(err.message);
setLoading(false);
});
}, []);

Render conditionally:

if (error) {
return <p>Error: {error}</p>;
}

Method 2: Fetch Data Using Axios

Axios is a powerful HTTP client library.

Install:

npm install axios

Example:

import axios from "axios";useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
setUsers(response.data);
setLoading(false);
})
.catch((error) => {
setError(error.message);
setLoading(false);
});
}, []);

Why Many Developers Prefer Axios:

  • Cleaner syntax
  • Automatic JSON parsing
  • Better error handling
  • Request cancellation support
  • Interceptors for authentication

Fetch Data on Button Click

Sometimes you don’t want data immediately.

Example:

const fetchUsers = () => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((data) => setUsers(data));
};<button onClick={fetchUsers}>Load Users</button>

This approach is useful for search systems and filters.


Display Data in a Clean UI

Better UI structure:

<div className="container">
{users.map((user) => (
<div className="card" key={user.id}>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Company: {user.company.name}</p>
</div>
))}
</div>

Basic CSS:

.container {
display: grid;
gap: 15px;
}.card {
padding: 15px;
border: 1px solid #ccc;
border-radius: 8px;
}

Handling Empty API Responses

Sometimes API returns an empty array.

Add condition:

if (!users.length && !loading) {
return <p>No users found.</p>;
}

Cleaning Up API Requests

When a component unmounts, unfinished requests may cause memory leaks.

Using AbortController:

useEffect(() => {
const controller = new AbortController(); fetch("https://jsonplaceholder.typicode.com/users", {
signal: controller.signal,
})
.then((res) => res.json())
.then((data) => setUsers(data)); return () => controller.abort();
}, []);

This prevents unnecessary errors.


Best Practices for Real Projects

  • Always use loading and error states
  • Separate API logic into services folder
  • Use environment variables for API URLs
  • Never hardcode sensitive tokens
  • Use async/await for cleaner code

Example with async/await:

useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch("API_URL");
const data = await response.json();
setUsers(data);
} catch (error) {
setError(error.message);
}
}; fetchData();
}, []);

Common Mistakes Beginners Make

❌ Forgetting dependency array in useEffect
❌ Not handling loading state
❌ Not checking response.ok
❌ Not adding key prop in lists
❌ Fetching inside render (wrong place)


Real-World Architecture (Intermediate Level)

Professional apps usually:

  • Create /services/api.js
  • Store all API calls there
  • Use custom hooks like useFetch
  • Use libraries like React Query or SWR

Example structure:

src/
├── components/
├── services/
│ └── userService.js
├── hooks/
└── App.js

This keeps the app scalable.

Conclusion

How to Fetch and Display API Data in React – Fetching and displaying API data is a foundational concept in React development. Once you understand how to request data, store it in state, and render it dynamically, you unlock the ability to build powerful real-world applications.

Throughout this guide, we explored multiple approaches — using the native fetch() method as well as the popular axios library. We also covered important concepts like loading states, error handling, conditional rendering, cleanup mechanisms, and code organization strategies.

As you continue learning React, you can explore advanced tools like custom hooks, React Query, or SWR for even more optimized data fetching. But the foundation you’ve learned here will always remain the backbone of API integration in React applications.

Want to learn more about React ?, Kaashiv Infotech Offers React course and more Visit Their website www.kaashivinfotech.com.

0 Shares:
You May Also Like