Introduction to useEffect Hook In ReactJS – Part Three

Introduction

In the previous article, we have learned about how to call useEffect only once and how to perform the cleanup. Now, in this article, we are going to learn about fetching data from API. 

Data Fetching using useEffect() hooks

As we have already learned about the Axios library in previous article sections, in this article, for getting the data using useEffect() hook, we will use the same library. 

So, to start using the Axios library, we first need to install using the below command,

npm install axios  

After successful installation of the Axios library, it will be added to the node_modules folder. 

Fetch Data from API using useEffect()

Here, we will use the Axios library to fetch data from API ‘https://reqres.in/’. This is the same API we use in our previous article to fetch data. Let’s look at the demo.

Create a new functional component named DataList.js.

import React,{useState,useEffect} from 'react'  
import axios from 'axios'  
  
function DataList() {  
  
    const[users,setUsers] = useState([])  
  
    useEffect(()=>{  
        axios.get("https://reqres.in/api/users")  
             .then(res=>{  
                 console.log(res)  
             })  
             .catch(err=>{  
                 console.log(err)  
             })  
    })  
    return (  
        <div>  
            <ul>  
                {  
                    users.map(user=> <li key={user.id}>{user.email}</li>)  
                }  
                  
            </ul>  
        </div>  
    )  
}  
  
export default DataList  

And, import the same in App.js. The output will be displayed as below.

useEffect Hook In ReactJS

Now, in the console, we can see that there is a warning that “setUsers() is assigned a value but never used” so, will now update the method in useEffect() method.

Now, the method will look like below.

useEffect(()=>{  
        axios.get("https://reqres.in/api/users")  
             .then(res=>{  
                 console.log(res)  
                 setUsers(res.data)  
             })  
             .catch(err=>{  
                 console.log(err)  
             })  
    })   

Now, run your application. It will be displayed as below.

useEffect Hook In ReactJS

As you can see there are only 6 records, but the console is getting an infinite loop so as we learn in the previous article, here we are just fetching records from API so this operation needs to be performed only once so adding an empty array as the second parameter in the useEffect() function.

useEffect(() => {  
        axios.get("https://reqres.in/api/users")  
            .then(res => {  
                console.log(res)  
                setUsers(res.data.data)  
            })  
            .catch(err => {  
                console.log(err)  
            })  
    },[])  

Now, the output will be like below.

useEffect Hook In ReactJS

useEffect() is calling only once when the component is mounted. Now, we will go in detail to fetch data based on user input. 

Now, in this example, we will be using  https://jsonplaceholder.typicode.com/, as the previous API has limited API calls.

Add an input textbox that will take email address and fetch data accordingly,

import React, { useState, useEffect } from 'react'  
import axios from 'axios'  
  
function DataList() {  
  
    const [user, setUser] = useState({})  
    const[id,setId] = useState(1)  
       
    useEffect(() => {  
        axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)  
            .then(res => {  
                console.log(res)  
                setUser(res.data)  
            })  
            .catch(err => {  
                console.log(err)  
            })  
    })  
  
    return (  
        <div>  
            <input type="text" value={id} onChange={e=>setId(e.target.value  
)}/>  
            <div>{user.title}</div>  
        </div>  
    )  
}  
  
export default DataList   

Now, the output will be displayed as below.

useEffect Hook In ReactJS

As we see in the console there is a warning as we have specified empty array but now in current, we need to call useEffect() whenever there is an update in id.

useEffect(() => {  
        axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)  
            .then(res => {  
                console.log(res)  
                setUser(res.data)  
            })  
            .catch(err => {  
                console.log(err)  
            })  
    },[id]) 

Now, check that the output is running as below.

useEffect Hook In ReactJS

Now, let’s add a button control on click of which data should be displayed.

import React, { useState, useEffect } from 'react'  
import axios from 'axios'  
  
function DataList() {  
  
    const [user, setUser] = useState({})  
    const [id,setId] = useState(1)  
    const [idOnClick,setIdOnClick] = useState(1)  
  
    const onClick = () => {  
        setIdOnClick(id)  
    }  
    useEffect(() => {  
        axios.get(`https://jsonplaceholder.typicode.com/posts/${idOnClick}`)  
            .then(res => {  
                console.log(res)  
                setUser(res.data)  
            })  
            .catch(err => {  
                console.log(err)  
            })  
    },[idOnClick])  
  
    return (  
        <div>  
            <input type="text" value={id} onChange={e=>setId(e.target.value)}/>  
            <button type="submit" onClick={onClick}>Get Data</button>  
            <div>{user.title}</div>  
        </div>  
    )  
}  
  
export default DataList  

Now, the output will be displayed as below.

Initially, it will display data with id 1

useEffect Hook In ReactJS

Later, on click of the button, the data will be updated,

useEffect Hook In ReactJS

FAQ Related to useEffect()

Q1: What is the purpose of useEffect() hook? 

The hook is used to tell React that after render method is called component needs to perform some action, it will include either fetching of data or updating DOM and so on. 

Q2: Why is useEffect() hook called inside a component? 

The main purpose of calling hooks inside component is because it can easily access props and state declared inside component without the help of additional API to use it.

Q3: Is useEffect() called on every render? 

useEffect() hook can be called on every render, but it is not compulsory. It can be called only once by using an empty array as a second parameter or can be called based on an update of props or state. It depends on user requirement when to call it. 

Summary

In this article, we have learned about getting from API using useEffect() hook in React Js.

Now in the next article, we will learn about the next hook useContext().

Any question or feedback or suggestion, please do comment and let me know.

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s