Better Programming

Advice for programmers.

Follow publication

Member-only story

REST API Consumption in React With Fetch, Axios, and Axios Hooks

Sahdev Garg
Better Programming
Published in
6 min readDec 29, 2021

--

Photo by Rob Fuller on Unsplash

There are various ways of consuming REST APIs in React but in this blog, we will be focussing on how we can consume REST APIs using two of the most popular methods:

  • Axios (a promise-based HTTP client)
  • Fetch API (a browser in-built web API).

We also discuss the hooks version of Axios using axios-hooks.

First, let’s create a sample react application to demonstrate Rest API consumption in React App.

The application is capable of calling an endpoint that gives random user info. For now, we only print the full name and email of the user.

import React,{useEffect,useState} from "react";

const RenderUserInfo = (props) => {
const { name, email } = props;
return (
<div>
<p>Name: {name}</p>
<p>Email: {email}</p>
</div>
);
};

const UserList = () => {

const [userList,setUserList] = useState([])

const apiCall=()=>{
// API logic goes here
}

useEffect(()=>{
apiCall()
},[])

return (<div>
{userList.map((item, index) => (
<RenderUserInfo name={item.name} email={item.email} key={index} />…

--

--

Sahdev Garg
Sahdev Garg

Written by Sahdev Garg

Gen AI Developer at AMEX with a passion for web development and DevOps automation. 🛠️👨‍💻

Write a response