Custom hook in reactjs

Sun Mar 19 2023

In React, a custom hook is a JavaScript function that uses one or more built-in hooks and/or other custom hooks to provide a specific functionality. Custom hooks allow you to extract and reuse logic across multiple components in your application, making it easier to maintain and scale your codebase.

In your react app, create a file useFetchData.js and paste the following code

import { useState, useEffect } from "react";

function useFetchData(url) {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {

      try {
        const response = await fetch(url);
        const json = await response.json();
      } catch (error) {


  }, [url]);

  return { data, isLoading, error };

export default useFetchData;

We imported useState and useEffect hooks from react. useFetchData accepts url. We created data, isLoading and error state with initial value as null, false and null respectively.

In useEffect we created a called a function fetchData which will get data from the url useFetchData function will receive. We have also passed url as useEffect dependency and return data, isLoading and error as object. Finally, we exported useFetchData as default export from this file.

Now we will fetch single todo from json placeholder So copy and paste the following code into the file where you would like to display data

import React from "react";
import useFetchData from "path-to-useFetchData-file";

const Home = () => {
  const {data, isLoading, error} = useFetchData(

  if (isLoading) {
    return <div>Loading...</div>;

  if (error) {
    return <div>Error: {error.message}</div>;

  return (
      {data && (

export default Home;

Here we called useFetchData hook and pass it the url. We also destructured data, isLoading and error. Here we are conditionally rendering title if data exists. You can use it to fetch arrays as well and then loop over data and display the result for each array item.

This will be useful if you want to make another api call and display the data in another route. All you will have to do is to call the custom hook and pass the url just like we did here.

Custom hooks can help you write cleaner, more modular code that is easier to maintain over time.


Privacy Policy

Developed By Farhan Farooq