Fetching Data in React Using APIs

 Introduction

Most real world React applications need data from a backend server or API.
For example:
  • User Details
  • Product Lists
  • Blog Posts
  • Weather Data
React provides the useEffect hook to handle these side effects like fetching data.

What is useEffect ?

useEffect is a React Hook used to run code after a component renders.

Common uses of  useEffect
  • Fetch data from APIs
  • Update the document title
  • Add event listeners
  • Run code when a component loads
Why Use useEffect for API Calls?

When a component loads,
  • React first renders the UI
  • Then useEffect runs
  • API data is fetched
  • UI updates with new data
Basic Syntax of useEffect

  • The empty array [] means run the code only once when the component loads

Example: Fetching Data from an API

Let's fetch users from a free API

Step by Step Example


Explanation of the Code

1. useState


  • Store API data
  • Initial empty
2. useEffect


  • Runs once when the component loads
  • Calls the API
3. fetch()

  • Sends request to API 
  • Converts responses to JSON
  • Saves data to state
4. Rendering the data


  • Loops through users.
  • Displays each user name.

Using Async/Await

 

  • Cleaner
  • Easier to read
  • Recommended for modern React
Handling Loading State


Common Mistaes to Avoid

  • Forgetting the dependency array
  • Calling API outside useEffect
  • Updating state without checking component lifecycle
When to use useEffect for APIs?

Use useEffect when,
  • Data should load on page load
  • Data depends on props or state
  • You need to sync UI with external data



Comments