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 Axios library, we first need to install using the below command
  1. 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.
  1. import React,{useState,useEffect} from 'react'  
  2. import axios from 'axios'  
  3.   
  4. function DataList() {  
  5.   
  6.     const[users,setUsers] = useState([])  
  7.   
  8.     useEffect(()=>{  
  9.         axios.get("https://reqres.in/api/users")  
  10.              .then(res=>{  
  11.                  console.log(res)  
  12.              })  
  13.              .catch(err=>{  
  14.                  console.log(err)  
  15.              })  
  16.     })  
  17.     return (  
  18.         <div>  
  19.             <ul>  
  20.                 {  
  21.                     users.map(user=> <li key={user.id}>{user.email}</li>)  
  22.                 }  
  23.                   
  24.             </ul>  
  25.         </div>  
  26.     )  
  27. }  
  28.   
  29. 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 the useEffect() method. Now, the method will look like below.
  1. useEffect(()=>{  
  2.         axios.get("https://reqres.in/api/users")  
  3.              .then(res=>{  
  4.                  console.log(res)  
  5.                  setUsers(res.data)  
  6.              })  
  7.              .catch(err=>{  
  8.                  console.log(err)  
  9.              })  
  10.     })   
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 learned in the previous article, here, we are just fetching the 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.
  1. useEffect(() => {  
  2.         axios.get("https://reqres.in/api/users")  
  3.             .then(res => {  
  4.                 console.log(res)  
  5.                 setUsers(res.data.data)  
  6.             })  
  7.             .catch(err => {  
  8.                 console.log(err)  
  9.             })  
  10.     },[])   
Now, the output will be like below.
 
useEffect Hook In ReactJS 
useEffect() is called only once when the component is mounted.
 
Now, we will go in details of how to fetch the data based on user input. 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.
  1. import React, { useState, useEffect } from 'react'  
  2. import axios from 'axios'  
  3.   
  4. function DataList() {  
  5.   
  6.     const [user, setUser] = useState({})  
  7.     const[id,setId] = useState(1)  
  8.        
  9.     useEffect(() => {  
  10.         axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)  
  11.             .then(res => {  
  12.                 console.log(res)  
  13.                 setUser(res.data)  
  14.             })  
  15.             .catch(err => {  
  16.                 console.log(err)  
  17.             })  
  18.     })  
  19.   
  20.     return (  
  21.         <div>  
  22.             <input type="text" value={id} onChange={e=>setId(e.target.value  
  23. )}/>  
  24.             <div>{user.title}</div>  
  25.         </div>  
  26.     )  
  27. }  
  28.   
  29. 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 that we have specified an empty array but now in current, we need to call useEffect() whenever there is an update in id.
  1. useEffect(() => {  
  2.         axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)  
  3.             .then(res => {  
  4.                 console.log(res)  
  5.                 setUser(res.data)  
  6.             })  
  7.             .catch(err => {  
  8.                 console.log(err)  
  9.             })  
  10.     },[id])   
Now, check that the output it is running as below.
 
useEffect Hook In ReactJS
Now, let’s add a button control, on click of which, the data should be displayed.
  1. import React, { useState, useEffect } from 'react'  
  2. import axios from 'axios'  
  3.   
  4. function DataList() {  
  5.   
  6.     const [user, setUser] = useState({})  
  7.     const [id,setId] = useState(1)  
  8.     const [idOnClick,setIdOnClick] = useState(1)  
  9.   
  10.     const onClick = () => {  
  11.         setIdOnClick(id)  
  12.     }  
  13.     useEffect(() => {  
  14.         axios.get(`https://jsonplaceholder.typicode.com/posts/${idOnClick}`)  
  15.             .then(res => {  
  16.                 console.log(res)  
  17.                 setUser(res.data)  
  18.             })  
  19.             .catch(err => {  
  20.                 console.log(err)  
  21.             })  
  22.     },[idOnClick])  
  23.   
  24.     return (  
  25.         <div>  
  26.             <input type="text" value={id} onChange={e=>setId(e.target.value)}/>  
  27.             <button type="submit" onClick={onClick}>Get Data</button>  
  28.             <div>{user.title}</div>  
  29.         </div>  
  30.     )  
  31. }  
  32.   
  33. export default DataList  
Now, the output will be displayed as below.
 
Initially, it will display the data with id 1.
 
useEffect Hook In ReactJS
Later, on click of the button, the data will be updated.
 
useEffect Hook In ReactJS 

FAQs 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?
 
The 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 ReactJS.
 
You can download source code attached to this article. Now in the next article, we will learn about the next hook, i.e., useContext().