React Custom Hook : useFetch()

Anas Reza
Towards Dev
Published in
2 min readDec 30, 2021

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Written by Anas Reza

Software Developer • Javascript is the key

Responses (1)

Write a response