Build your own Custom Hook in React.JS ๐Ÿš€

Build your own Custom Hook in React.JS ๐Ÿš€

Build your own Hooks

ยท

3 min read

React Hooks gives you ability to build your own custom Hooks where you can separately keep the components logic and reuse the function in other components as well. As the name signifies Custom Hooks allows you to build the hook according to your use-case. Suppose a pagination component can be turned into a Custom Hook wherein we can pass the page size and page number and it can return you the total number of pages with the filtered data etc. Similarly we can make a Custom Hook for Api calls which have homogenous response format.

Let's start by creating a Custom Hook which accepts the Api Source as the argument and returns the result. Further we will see how to use a Custom Hook.

1. Creating a Custom Hook

  • Custom Hook is a JavaScript function and it's name always starts with "use". We will be creating useFetchData Hook in this example.
import React,{useState,useEffect} from 'react'

const useFetchData=(apiSrc)=> {
    const [data,setData]=useState(null)
    useEffect(()=>{
       fetch(apiSrc)
       .then((res)=>res.json())
       .then((data)=>{
        console.log(data)
        setData(data)
       })
    },[])
    return data;
}

export default useFetchData
  • Create a useFetchData. function which takes Api Source as an argument.

  • We use fetch() to get the data from the Api which we got from the argument.

  • Use a state variable in which the response of the Api will be stored. Here we storing it in the "data" state variable.

  • Finally we return the state variable which contains the data fetched from the Api.

2. Using a Custom Hook in other Components

  • Using a Custom Hook is equivalent to using a function , you need to pass the argument over which you want to obtain the result.

  • Now you can go to your App.js and us the Hook:

import useFetchData from './components/useFetchData';
function App() {
  const apiData=useFetchData('https://jsonplaceholder.typicode.com/posts')
  console.log(apiData)
  return (
    <div className='App'>
      <div className='title'>Api Data</div>
      {apiData?.map((item,index)=>{
        return <>
        <div className='titleContainer'>{item.title}</div>
        </>
      })}
    </div>
  );
}
  • Import the useFetchData hook into your component.

  • Declare a variable that subscribes to the Custom Hook and pass the Api Source as a parameter to it.

  • The variable now contains the response from the api which as array type.

  • Loop over the Api data in your jsx to view the results.

Screenshot 2022-10-22 at 1.07.53 AM.png

You have successfully created your first Custom Hook. You can further add / modify the Hook accordingly. You can start by passing one more argument which can return the total count of the elements in the response array. You can also write logic to filter some data from the response inside the hook and can return the filtered data as well. Then in your component where you are using the Custom Hook you can extract the filtered data as well.

Conclusion:

Custom Hooks are an efficient way of extracting common code between two functions into a separate function. They follow the conventional design of React Hooks and are not a feature. They provide functionality to re-use stateful logic. Each time we make a call to Custom Hook all the state and useEffect inside the Hook work in isolation to the component. Custom Hooks provision more flexibility in logic sharing and easier to use.

ย