React Custom Hook : useFetch()
When you have a logic that needs to be used by multiple components, we can always turn it into a custom hook. We can say a custom hook is a re-usable component that will act as a utility for the application.
Suppose we have multiple components where we want to fetch some data from the server and display it on UI. For that, we won’t be writing fetch() inside every component and handling its response and error.
fetch("https://example.com/products")
.then((res) => res.json())
.then((data) => setData(data))
.catch((err) => console.log(err));
Let’s develop a custom hook that will improve this redundancy.
usefetch.js (custom hook)
import { useState, useEffect } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => setData(data))
.catch((err) => console.log(err));
}, [url]);
return [data];
};
export default useFetch;
Here we’ve created a useFetch component to be used as a custom hook. Whenever this component gets initialized, useEffect will be invoked and inside that fetch function will expect a URL to make HTTP request.
Both the success and error handling will be handled in one place.
Once the response is received, it will store the data in a local variable and return it.
Let’s go to the second part, how to use this custom hook in any of your component.
import useFetch from "./useFetch";
const YourComponent = () => {
const [products] = useFetch("https://example.com/products");
return (
<div>{products && products.map((prod) => {
return <ul><li key={prod.id}>{prod.title}</li></ul>;
})}
</div>
);
};
Here we have imported useFetch and passed URL to it.
useFetch component will execute and make an HTTP request to this URL and return the response which will be stored in products variable.
Now we can reuse this custom Hook in any component to fetch data from any URL.