Table of contents
1.
Introduction
2.
React Hooks
3.
Custom Hooks
3.1.
Advantages
3.2.
Example 1
3.3.
Example 2
4.
Frequently Asked Questions
4.1.
How to declare a custom hook?
4.2.
Can we use react hooks in class-based components?
4.3.
When were hooks introduced in react?
4.4.
What are the different categories of hooks in react?
4.5.
Do hooks increases code reusability?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Build Your Own Custom Hooks

Author dhananjay
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The concept of Hooks was introduced in React 16.8 version, which is highly appreciated by React users due to the benefits we can get from React Hooks.

There are two types of Hooks we can use in React.

  • Inbuilt Hooks
  • Custom Hooks
introduction image

This blog will discuss Custom Hooks in React and why we need Custom Hooks. We will also learn how to implement Custom Hooks using React. But first, let's understand the Hooks in general.

React Hooks

The main benefit of using React Hooks in your projects is that it removes code redundancy and adds code reusability. These React Hooks are also plain Javascript objects which we can include in our functional React components.

For example: Let's say you want to keep track of the state of a particular function component in your project. Here we can use the useState() Hook to track the state.

function App() {
    const [state, updatedstate] = useState(0);
    return (
        <div>
            <p>Click Counter {state}</p>
            <button onClick={() => updatedstate(state + 1)}>
                Click here
            </button>
        </div>
    );
}
You can also try this code with Online Javascript Compiler
Run Code


We will initialize the state as 0 in the above component. As you can see, we have given 0 as a parameter in useState(). After this, we will need to use two variables, state, and updatedstate

The state variable will be equal to the current state of the component, and updatedstate will update the state of the component. To learn more about useState(), check out the link.

Output

click counter output

After clicking three times:

click counter output

Before React 16.8, you have to write your code to track the state of the class components. Remember that we cannot use Hooks in class-based components in react.

The useState() Hook is one of the inbuilt Hooks we can use in our React function components. There are many more components that you can use to learn about them; go to this link.

Our goal is to learn about Custom Hooks. Now that we have understood why we use Hooks, let's learn how to make our Hook react.

Custom Hooks

As mentioned, Hooks help remove code redundancy and add code reusability.  With Custom Hooks, we can reuse the code of stateful logic in different components without writing it repeatedly.
Before Custom Hooks, we have to use higher-order components or render props to use the stateful logic.

The name of the Custom Hooks starts with ‘use’ like uselogic(). We can create a separate.js file and add the create function in that file, and then we can import it as Hook in our desired component. Let's create a custom Hook to understand it better.

Advantages

Let us know the advantages of using custom hooks in your react project.

  • Custom hooks increase the code reusability in the project, which leads to saving time during development.
     
  • With the help of custom hooks, we can make our code more readable. Since we do not have to depend on the methods like higher-order components or render props to write stateful logic and make our code complex.
     
  • Using custom hooks can make the testing of our project more efficient because we can easily pinpoint the error component if we get any in our project.

Example 1

In this example, we will dynamically calculate the size of the window screen and display the result on the screen as “width/height”.

App.js

import useWindowSize from "./windowresize";
function App() {
    const size = useWindowSize();
    return (
        <div>
            {size.width}px / {size.height}px
        </div>
    );
}
export default App;
You can also try this code with Online Javascript Compiler
Run Code


windowresize.js

import { useState, useEffect } from "react";
export default function useWindowSize() {
    const [windowSize, setWindowSize] = useState({
        width: undefined,
        height: undefined,
    });
    
    useEffect(() => {
        function handleResize() {
            setWindowSize({
                width: window.innerWidth,
                height: window.innerHeight,
            });
        }
        window.addEventListener("resize", handleResize);
        handleResize();
        return () => window.removeEventListener("resize", handleResize);
    }, []);
    return windowSize;
}
You can also try this code with Online Javascript Compiler
Run Code

 
Output

window resize example

After resizing the tab window, we will see the different measurements on the screen.

window resize example

In the above example, we have a hook that returns the current window's size. Let’s understand the logic. 

  • When we call this hook, it will first get the current window's size to return it.
     
  • Second, it will attach the event listener to the window’s object and listen to resize the event. window.addEventListener("resize", handleResize)
     
  • When the event happens, the hook detects the window’s new size and returns it. 
     
function handleResize() {
	setWindowSize({
		width: window.innerWidth,
		height: window.innerHeight,
	});
}
You can also try this code with Online Javascript Compiler
Run Code

 

  • This would be repeated every time whenever the resize event happens. 
     
  • Custom hooks can use the other React hooks. We can use the useState hook to store the latest window size in a state and return the value of this state. 
     
  • We can also use the useEffect hook to attach the event listener for resizing events.

Example 2

Let's assume you want to fetch the data from an API, and you need to display that data in different components of your project. If you need to learn about custom hooks, you might fetch the data in each component and display it.

Let's create a hook name useRandomImages to fetch and return the data or response from the API and display it in the App.js component.

random.js

In the random.js file, we will create our custom hook ‘useRandomImage’. In the useRandomImage function, we will create another function and fetch the data from the API https://dog.ceo/api/breeds/image/randomThis API will return the images of random dogs as the response.

import { useState } from "react"
import axios from "axios";

const useRandomImages = ( ) =>
{
    const [images, setimages] = useState("");

    const dogdata = async ()=>{
        const response = await axios.get("https://dog.ceo/api/breeds/image/random")
            setimages(response.data)
    }
    return {images, dogdata};
}

export default useRandomImages;
You can also try this code with Online Javascript Compiler
Run Code


We manage the state of the project with the useState() hook. In useState(), we will use two variables, images, and setimages. We will use the setimages to update the state whenever we call the dogdata function to fetch the response.

At last, we will return the images and dogdata.

App.js

import useRandomImages from "./randomimages";
function App() {
    const {images,dogdata} = useRandomImages()
    return (
    <div >
        <div>
            <img style={images ? {width:500,height:300} : null} src={images.message}></img>
        </div>
        <button onClick={dogdata}>change</button>
    </div>
    );
}
export default App;
You can also try this code with Online Javascript Compiler
Run Code


When we click the change button, it will call the dogdata function in useRandomImages and fetch the data. Then in the hook, we will update the state, and we can access the state in the App.js by making src=”{images.message}” in the <img> tag. Here .message has the URL of the image.

Output

Initial output

example 2 code output

After clicking on the change button.

example 2 code output

Again clicking on the change button.

example 2 code output

These are a few examples of how we can create Custom Hooks in react. 

You can create Custom Hook and use it whenever you want in the project. But make sure you are following the below rules for creating a Custom Hook.

  • Do not use Hook in the loop, if-else, or nested functions. Only apply the Hook at the top level.
     
  • Do not call the Hook in a Javascript function. Only call the Hook in React Function component because it is the valid way of calling the Hook.

Frequently Asked Questions

How to declare a custom hook?

You have to add “use” with the name of your hook because that is how we identify it; for example, “useWindow” here window is the name added with “use”.

Can we use react hooks in class-based components?

No, we cannot use the react hooks in the class-based component in react.

When were hooks introduced in react?

Hooks were introduced in the 16.8 version of the react to add more functionality in function-based components.

What are the different categories of hooks in react?

There are two categories of hooks in react inbuilt and custom hooks.

Do hooks increases code reusability?

Custom hooks increase the code reusability in the project, saving time during development.

Conclusion

In this blog, we have discussed the React Hooks, and also we have discussed the Custom Hooks in React and how we can implement them.

To learn more about React, check out the following article.

To learn more about DSA, competitive coding, and many more knowledgeable topics, please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences and interview bundle for placement preparations.

Happy Coding!

Live masterclass