How to Create a Custom Hook in React

If you came on this post as a result of How to Create Custom hook in react and you are unfamiliar with hooks. I strongly advise you to read the two articles linked ahead. In which we go over generic hooks in React as well as several crucial and basic hooks in React.

I am going to show you how to make a custom hook in React in this tutorial. Because utilizing React in this manner has the potential to drastically alter the way you design components.

Without a custom hook

Assume we have a feature in our component that allows us to access the Window’s width when the user resizes the screen. We need to know how big the screen is, whether it’s small, medium, or large.

We can write something like this:

const LayoutComponent = () => {
    const [onSmallScreen, setOnSmallScreen] = useState(false)

    useEffect(() => {
        checkScreenSize();
        window.addEventListener("resize", checkScreenSize);
    }, []);

    let checkScreenSize = () => {
        setOnSmallScreen(window.innerWidth < 700);
    };

    return (
        <div className={`${onSmallScreen ? "small" : "large"}`}>
            <h1>Hello from Default Hooks</h1>
        </div>
    );
};

Without a custom hook the main problem is/are:

The component is in perfect working order. It determines the size based on the width being less than 700. Consider what would happen if I needed the same screen size check in another component. Is it necessary for me to copy-paste the code? I’m sure I can! However, this destroys React’s code reusability. Instead, we can put this functionality inside a custom hook and utilize it anywhere we choose.

Creating with the custom hook

Because the hooks are just JS Functions, they don’t require the presence of a React component.

I’ll create a new file called useWindowsWidth.js:

import { useState, useEffect } from "react";

const useWindowsWidth = () => {
    const [isScreenSmall, setIsScreenSmall] = useState(false);

    let checkScreenSize = () => {
        setIsScreenSmall(window.innerWidth < 700);
    };

    useEffect(() => {
        checkScreenSize();
        window.addEventListener("resize", checkScreenSize);

        //Cleanup
        return () => window.removeEventListener("resize", checkScreenSize);
    }, []);

    return isSreenSmall;
};

export default useWindowsWidth;

Using the hook

This functionality is extractes from the useWindowsWidth method. We can now import it and utilize it wherever we want!

import React from "react"
import useWindowsWidth from "./useWindowsWidth.js"

const MyComponent = () => {
    const onSmallScreen = useWindowsWidth();

    return (
        //Return some element
    )
}

I can now use useWindowsWidth whenever I need to know the screen size (). Isn’t this fantastic? You might, for example, import a function rather than create the complete code from start. You can even use props to make this code more dynamic by altering the hard-coded screen size. woosh! with props.screenSizeCheck You may use the component in any location and in any size you desire.

FAQ

Do we have to start our custom hooks name with ‘use’?

Well, YES! According to the official React documentation:

A custom Hook, unlike a React component, does not require a signature. We may choose what it accepts as parameters and what it should return, if anything. To put it another way, it’s just like any other function. Its name should always begin with the word “use” so that you can see right once that it follows the Hooks requirements.

Do the same custom hooks in two components share a state?

Nupp! Rest assured. If you use the same custom hooks in two components, they WILL NOT* share state.

Summary

When creating React Code, custom hooks allow you to be as creative as you want. You can extract and share logic in a manner that class components could not. Yes, this also allows us to create highly “useful” functions that may be utilized in many locations across the application.

That’s all about this article if you want to learn React then go to our react category where you find all React articles

Leave a Comment