Custom Hooks in React
usefetch() hook

I am frontend developer from India.
In this article we are going to see a reuseable custom hook for fetching the data from API

Why write a custom hook for fetching data?
Let us suppose we are fetching data from multiple APIs in a single react app. While writing code for fetching data from multiple APIs we observe that there is a fair amount of boilerplate/logic. To avoid writing similar code multiple times we will outsource that boilerplate/similar code on a separate file.
Old code
The normal way of fetching data without a custom hook is as follows:
import { useState,useEffect } from "react";
import "./styles.css";
export default function App() {
const[quote,setquote]=useState([])
useEffect(() => {
const getquote=async()=>{
const temp=await fetch(`https://api.quotable.io/random`)
.then(res=>res.json());
setquote(temp)
}
getquote()
}, []);
return (
<div className="App">
{quote.content}
</div>
);
}
In this code,we are using useState() hook to keep track of data and useEffect() hook to run all that code.Lastly,we are using fetch() to fetch the data.
New way
Create a new file useFetch.js. Now let us write a boilerplate for fetching data.
//usefetch()
import { useEffect, useState } from "react";
function useFetch(url) {
const [data, setData] = useState([]);
useEffect(() => {
const getquote = async () => {
const temp = await fetch(url).then((res) => res.json());
setData(temp);
};
getquote();
}, [url]);
return { data };
}
export default useFetch;
You may have seen some code changes the useFetch function accepts URL from where we get the data. Lastly, our useFetch returns our data.
Using useFetch() in our component
So, now we will import our useFetch() component in our App.js file and pass the URL we want to get data from.
import "./styles.css";
import useFetch from "./useFetch";
export default function App() {
const { data: quote } = useFetch(`https://api.quotable.io/random`)
return (
<div className="App">
{quote.content}
</div>
);
}
Now, our code is much cleaner.

Conclusion
Custom hooks help us to make our code much cleaner. One can use react hooks inside the custom hooks.
That's it Thank you for reading.







