useReducer() Hook In ReactJS - Part Three

Introduction

 
In the previous article, we have learned about using multiple useReducer() hooks to pass state among multiple components. Now, in this article, we will learn about fetching data using API.

Fetching data using useReducer() hook

 
Using useReducer() hook, we are going to fetch data from API. We have performed data fetching in the previous article from ‘https://reqres.in’ API using Axios library; here, we will be using useReducer() hook for fetching data.
 
Let’s look at the example first with the use of useEffect() hook with the same example we used for useReducer() hook,
 
First, to start with, we need to install the Axios library using a command mentioned below.
 
npm install axios
 
After successful installation, create a component named GetData.js.
  1. import React, { useState, useEffect } from 'react'  
  2. import axios from 'axios'  
  3.   
  4. function GetData() {  
  5.     const [loading, setLoading] = useState(true)  
  6.     const [error, setError] = useState('')  
  7.     const [user, setUser] = useState({})  
  8.   
  9.     useEffect(() => {  
  10.         axios.get('https://reqres.in/api/users/2')  
  11.             .then(response => {  
  12.                 setLoading(false)  
  13.                 setUser(response.data.data)  
  14.                 setError('')  
  15.             })  
  16.             .catch(error => {  
  17.                 setLoading(false)  
  18.                 setUser({})  
  19.                 setError('Something went wrong')  
  20.             })  
  21.     }, [])  
  22.     return (  
  23.   
  24.         <div>  
  25.             {loading ? 'Loading!! Please wait' : user.email}  
  26.             {error ? error : null}  
  27.         </div>  
  28.     )  
  29. }  
  30.   
  31. export default GetData   
Import the same in App.js.
  1. import React from 'react';  
  2. import './App.css';  
  3. import GetData from './components/GetData';  
  4.   
  5. function App() {  
  6.    
  7.   return (  
  8.     <div className="App">  
  9.       <GetData/>  
  10.     </div>  
  11.   );  
  12. }  
  13.   
  14. export default App;   
The output will be displayed as below.
 
Now, add an incorrect URL for error view.
  1. useEffect(() => {  
  2.         axios.get('https://reqrese.in/api/users/2')  
  3.             .then(response => {  
  4.                 setLoading(false)  
  5.                 setUser(response.data.data)  
  6.                 setError('')  
  7.             })  
  8.             .catch(error => {  
  9.                 setLoading(false)  
  10.                 setUser({})  
  11.                 setError('Something went wrong')  
  12.             })  
  13.     }, [])  
This will display the error message due to incorrect API URL.
 
Now, look at the demo using useReducer() hook.
 
Create another component named GetData_Reduce.js.
  1. import React, { useEffect, useReducer } from 'react'  
  2. import axios from 'axios'  
  3.   
  4. const initialState = {  
  5.     user: {},  
  6.     loading: true,  
  7.     error: ''  
  8. }  
  9.   
  10. const reduce = (state, action) => {  
  11.     switch (action.type) {  
  12.         case 'OnSuccess':  
  13.             return {  
  14.                 loading: false,  
  15.                 user: action.payload,  
  16.                 error: ''  
  17.             }  
  18.         case 'OnFailure':  
  19.             return {  
  20.                 loading: false,  
  21.                 user: {},  
  22.                 error: 'Something went wrong'  
  23.             }  
  24.   
  25.         default:  
  26.             return state  
  27.     }  
  28. }  
  29.   
  30. function GetData_Reduce() {  
  31.     const [state, dispatch] = useReducer(reduce, initialState)  
  32.   
  33.     useEffect(() => {  
  34.         axios.get('https://reqres.in/api/users/2')  
  35.             .then(response => {  
  36.                 dispatch({ type: 'OnSuccess', payload: response.data.data })  
  37.             })  
  38.             .catch(error => {  
  39.                 dispatch({ type: 'OnFailure' })  
  40.             })  
  41.     }, [])  
  42.   
  43.     return (  
  44.         <div>  
  45.             {state.loading ? 'Loading!! Please wait' : state.user.email}  
  46.             {state.error ? state.error : null}  
  47.         </div>  
  48.     )  
  49. }  
  50.   
  51. export default GetData_Reduce   
The output will be the same as we saw before using the useState() hook.
 
First, it will display the loading screen.
 
Once the data is loaded from API, the data will be displayed on the screen.
 
Now, update the code and modify with incorrect API.
  1. useEffect(() => {    
  2.        axios.get('https://reqrese.in/api/users/2')    
  3.            .then(response => {    
  4.                dispatch({ type: 'OnSuccess', payload: response.data.data })    
  5.            })    
  6.            .catch(error => {    
  7.                dispatch({ type: 'OnFailure' })    
  8.            })    
  9.    }, [])     
In case any error occurs, the error screen will be displayed as below.
 
So, it will state to a conclusion about using useState() hook and using useReducer() hook.
 

What is the difference between useState() and useReducer() hook?

 
Below, we will see in which scenario which hook will be used in which scenario,
 
Scenario
useState()
useReducer()
Type of state
Use it when working with Number, Boolean, and String
Use it when working with object or Array
Number of state Transition
useState hook has only one or two transitions so it should be used when you have only 1 or 2 setState calls
useReducer() hook should be used when many transitions so it must be used when we have many setState that need to be called
Related State Transition
No related transition
It includes state transition
Business Logic
useState has no business logic
When your application involves complex data transformation or manipulation that this should be used
Local vs Global
When dealing with a single component and need to perform operations locally than useState should be used
When want to deal with multiple components for passing data from one component to another then useReducer() is a better approach.
 

Summary

 
In this article, we have learned about fetching data from API using useReducer() hook and where we can use  the two i.e) useReducer() and useState() hook. You can download the source code attached along with this article. Now in the next article, we will learn about another hook named useCallback() hook along with its usage.