Fetching Data from APIs with useEffect

In modern React apps, we often use useEffect to fetch data from an API when the component loads.

✅ Example: Fetching Users from an API

Here’s a simple component that fetches user data from a public API:

import { useEffect, useState } from "react";

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true); // for loading state

  useEffect(() => {
    // Fetch data when component mounts
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((data) => {
        setUsers(data);        // Save the data
        setLoading(false);     // Turn off loading
      })
      .catch((error) => {
        console.error("Error fetching users:", error);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <p>Loading users...</p>;
  }

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map((u) => (
          <li key={u.id}>{u.name}</li>
        ))}
      </ul>
    </div>
  );
}

🔍 What’s Happening Step-by-Step?

1. useState([])

  • Keeps track of the users list
  • Starts empty ([])

2. useEffect(() => { fetch(...) }, [])

  • Runs once, when component loads
  • Sends a GET request to the API
  • Saves the result in state via setUsers

3. loading state

  • While data is loading, we show a “Loading…” message
  • Once data arrives, we render the list

📦 API Used in Example

We used this fake API (for testing):

🌐 https://jsonplaceholder.typicode.com/users

Returns 10 fake users like:

[
  {
    "id": 1,
    "name": "Leanne Graham"
  },
  ...
]

✅ Handling Errors

Always add .catch() to handle failed requests gracefully (e.g., no internet).

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *