Avoid UseEffect To Fetch API Data Using React Custom Hook

Hello devs,

In this react js tutorial, I am going to share a short way to fetch API data in react js. Fetch API or Axios is available to make fetch data in javascript applications. So in this example, I will share with you that how we can fetch data using react custom hook react-fetch-hook package.

It is always better to make a clean code and short syntax in your application, and you might realize that using useEffect over and over again is tedious, even sometimes it confuses many developers.

How we can fetch data using useEffect:

useEffect(() => {
  axios.get("https://randomuser.me/api/")
      .then((response) => console.log(response.data));
},[]);

 

But in react, here we have a more clear way to fetch data. Using a third library react-fetch-hook allows us to fetch data and cut down on our reused code.

//install
npm install react-fetch-hook

//or

yarn add react-fetch-hook

//import
import useFetch from "react-fetch-hook"

//and use

const { isLoading, data, error } = useFetch("https://swapi.co/api/people/1");
console.log(data);

 

Read also: Make Your If Condition More Beautiful in JavaScript

 

Hope it can help you.

 

#react-js