Shamaayil Ahmed
Shamaayil Ahmed


Shamaayil Ahmed

React Custom Hooks

React Custom Hooks

Shamaayil Ahmed's photo
Shamaayil Ahmed
ยทFeb 12, 2021ยท

4 min read

Play this article

React Hooks are v16.8 specification which allows certain backward compactible functionalities without any use of class based ordering.

Let's see how to build a customized hook.


Hooks ain't constrained to those built by react core team. We can build our own hooks and specify the behind the hood functionalities, arguments, scopes and whatsoever.

Hooks are mere functions but the fact that they go easily with the react lifecycle, and can be instantiated whenever a functional component is rendering, makes custom hooks special.

Custom Hook

If we could recall the react hooks streak post in my blogs, those patterns and best practices are to be followed while creating a custom one.

  • Naming conventions to begin with 'use' keyword
  • Include the functionalities in a separate file
  • Get the apt arguments
  • Return simple data structures

Steps to follow for building a custom hook is as follows:

  1. Create a separate files with the name of the hooks and define the functionalities to be undergone with specified arguments and return a simple data structure.

  2. Import the file in the component where the functionality is required and the make sure the input are avail.

  3. Destructure the required data by calling the hook and do whatever with the data.

Custom hook in action

Here we build a useFetch() hook that takes in the url and returns the array of data as products, and a boolean loading.


import { useState, useEffect } from 'react';

export const useFetch = (url) => {
  const [loading, setLoading] = useState(true)
  const [products, setProducts] = useState([])

  const getProducts = async () => {
    const response = await fetch(url)
    const products = await response.json()

  useEffect(() => {
  }, [url]);

  return { loading, products };

The useFetch() hook is consumed in the below component to display the fetched data.


import React, { useState, useEffect } from 'react'
import { useFetch } from './useFetch'

const url = ''

const Example = () => {
  const { loading, products } = useFetch(url);
  return (
      <h2>{loading ? 'loading...' : 'data'}</h2>

export default Example

Major Takeaway

We are all good to build react hooks with our own functionalities and needs just follow on with some best practices

Let's connect ๐Ÿ”—

Catch me here ๐Ÿ‘‡

Hope you all liked the post, share your impressions and queries below ๐Ÿ™Œ

Share this