Fetch API data using useEffect React Hook

Today we’ll show you how to fetch API data using useEffect React Hook. In the previous article, we have provided the examples of the useEffect React Hook.

Here, we will see how to place an API call using useEffect and get the data from the API on demand using React Hooks. Let’s take an example where we will use the button and input field to get a record by id via API. If the input field is empty then we will fetch all the records.

Fetch API data using useEffect

  1. Create a react application
  2. Design a form
  3. Create an API to fetch data
  4. Output

1. Create a react application

First, we will create a react application using the create-react-app package. Run the following command to create a react app.

2. Design a form

Let’s design a simple form to fetch the API data. We will use the input field and button whereas the button will be used to fetch the data by id. If the input field will be empty then we will fetch all the records. So we will change the button text conditionally based on the input value.

3. Create an API to fetch data

Now, we’ll create an API to fetch data and call that API using useEffect React Hook. We’ll fetch all records on page load. For the demo purpose, we’ll use the JSONPlaceholder fake API.

Here, we have changed the API URL dynamically based on the id and also stored the response in the state variable in array format. We have passed the id as dependency parameter in the useEffect to conditionally run the code using useEffect.

4. Output

Let’s combine all code together and see how it works.

App.js

Run the application and check the output in the browser.

Output - Fetch API data using useEffect React Hook - Clue Mediator
Output – Fetch API data using useEffect React Hook – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

2 Responses

  1. valith syed s says:

    sir , i m learn HTML, CSS, JS but react js very hard one. o i think u have one you tube channel plz one video for react course and also js or type script course .

Leave a Reply

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