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.
- import React, { useState, useEffect } from 'react'
- import axios from 'axios'
-
- function GetData() {
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
- const [user, setUser] = useState({})
-
- useEffect(() => {
- axios.get('https://reqres.in/api/users/2')
- .then(response => {
- setLoading(false)
- setUser(response.data.data)
- setError('')
- })
- .catch(error => {
- setLoading(false)
- setUser({})
- setError('Something went wrong')
- })
- }, [])
- return (
-
- <div>
- {loading ? 'Loading!! Please wait' : user.email}
- {error ? error : null}
- </div>
- )
- }
-
- export default GetData
Import the same in App.js.
- import React from 'react';
- import './App.css';
- import GetData from './components/GetData';
-
- function App() {
-
- return (
- <div className="App">
- <GetData/>
- </div>
- );
- }
-
- export default App;
The output will be displayed as below.
Now, add an incorrect URL for error view.
- useEffect(() => {
- axios.get('https://reqrese.in/api/users/2')
- .then(response => {
- setLoading(false)
- setUser(response.data.data)
- setError('')
- })
- .catch(error => {
- setLoading(false)
- setUser({})
- setError('Something went wrong')
- })
- }, [])
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.
- import React, { useEffect, useReducer } from 'react'
- import axios from 'axios'
-
- const initialState = {
- user: {},
- loading: true,
- error: ''
- }
-
- const reduce = (state, action) => {
- switch (action.type) {
- case 'OnSuccess':
- return {
- loading: false,
- user: action.payload,
- error: ''
- }
- case 'OnFailure':
- return {
- loading: false,
- user: {},
- error: 'Something went wrong'
- }
-
- default:
- return state
- }
- }
-
- function GetData_Reduce() {
- const [state, dispatch] = useReducer(reduce, initialState)
-
- useEffect(() => {
- axios.get('https://reqres.in/api/users/2')
- .then(response => {
- dispatch({ type: 'OnSuccess', payload: response.data.data })
- })
- .catch(error => {
- dispatch({ type: 'OnFailure' })
- })
- }, [])
-
- return (
- <div>
- {state.loading ? 'Loading!! Please wait' : state.user.email}
- {state.error ? state.error : null}
- </div>
- )
- }
-
- 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.
- useEffect(() => {
- axios.get('https://reqrese.in/api/users/2')
- .then(response => {
- dispatch({ type: 'OnSuccess', payload: response.data.data })
- })
- .catch(error => {
- dispatch({ type: 'OnFailure' })
- })
- }, [])
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.