React Data fetching using Axios with Hooks

Purti Aggarwal
4 min readOct 1, 2023

--

In this article we will learn how to server data on our client side(In React using Axios and simple react hooks (i.e., UseEffect and UseState).

Before dive into practical part lets first focus on some important defination

  1. React Hooks:
    React Hooks introduced in React version 16.8. It is just a replacement for the class based component. React Hooks help us to maintain the react life cycles in function based components .

In this article we will use two important hooks

a. UseEffect: As you understand by its name UseEffect means synchronized with the effects. In simple language useEffect uses to handle the effects of data fetching and any change in DOM. This function run everytime when the DOM renders. we can run this function using the dependency array which have the control for rendening the DOM. UseEffect is an alternative to ComponentDidMount, ComponentDidUpdate, ComponentDidUnmount.

useEffect(<function>, <dependency>)

useEffect(() => {
//Runs only on the first render
}, []);


useEffect(() => {
//Runs every time when the depency changes.
}, [dependecy]);

b. UseState: UseState allow us to save state data in functional component. UseState accept the initial value and return two values :

Current State

Value Updating State

const [color, setColor] = useState("");

// color => current state
//setColor => value Updating State
//Initial state for color is empty string

2. Axios:
Axios is the library use to make API request from frontend using promise to get the server data. Axios is better in error handle also.

Lets Dive into the code

Axios is very easy to integrate into the existing React Project.

First Step: Create a react project using command.

npx create-react-app my-react-app

Open your project and do start your project.

Now we will write simple code for fetching data on rendering the page.

Second Step: Remove the code in app.js and install the axios library in your project.

npm install axios

Now first import React , UseEffect and useState from ‘react’ library and axios from axios.

import React, { useEffect, useReact } from 'react';
import axios from 'axios';

...

Third Step: let call an API in useEffect and show the data on rendering the component.



// Import necessary modules and libraries
import React, { useState, useEffect } from "react"; // Import React and related hooks
import axios from "axios"; // Import Axios library for making HTTP requests
import "./App.css"; // Import a CSS file (assuming it's for styling)

// Define the main functional component named "App"
function App() {
// Define a state variable 'data' using the 'useState' hook, initialized as an empty array
const [data, setData] = useState([]);

// Use the 'useEffect' hook to perform side effects when the component mounts
useEffect(() => {

// Call the 'fetchData' function when the component mounts (empty dependency array)
fetchData();
}, []); // Empty dependency array ensures this effect runs only once, when the component mounts

// Define an asynchronous function 'fetchData'
const fetchData = async () => {
// Send an HTTP GET request to the specified URL
const response = await axios.get(
"https://fakerestapi.azurewebsites.net/api/v1/Activities"
);

// Log the response from the API to the console
console.log("response", response);

// Update the 'data' state with the data from the API response
setData(response.data);
};

// Render the component's content
return (
<div className="App">
{/* Start of a <div> element with the CSS class "App" for styling */}
<ul>
{/* Start of an unordered list (<ul>) element */}
{data.map((item, index) => (
// Start of a JavaScript map() function applied to the 'data' array
<li key={index}>
{/* Start of a list item (<li>) element. 'key' is a unique identifier used for React rendering optimizations. */}
{item.title}
{/* Display the 'title' property of each 'item' in the list */}
</li>
// End of the list item (<li>) element
))}
{/* End of the JavaScript map() function */}
</ul>
{/* End of the unordered list (<ul>) element */}
</div>
// End of the <div> element with the CSS class "App"
);
}

// Export the 'App' component as the default export
export default App;

Now just go to the browser and hit http://localhost:3000/ then the magic happens 😱

This is how your Data looks like.

--

--