Let’s Create a Custom Hook in React ‍

Posted on

Hi all
So after quite a break, we are back with another article in the React Series with two awesome articles about hooks. If you have stumbled upon this article from a reference and don’t know what hooks are, I would definitely suggest to first try our those two articles at the given link where we have discussed deeply about general Hooks in React and about some essential and Basic Hooks in react

In this article, we are about to explain how can you create a custom hook in React. Because using React this way, might really change the way you develop components So first thing first, What are hooks? Well, the answer is here . So let’s just skip that part and directly jump next.



Without a custom hook

Let’s imagine that we have a functionality in our component to retrieve the Window’s width when the user resizes the screen. We need to know if the screen is 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>
    );
};
Enter fullscreen mode

Exit fullscreen mode



The Problem

The component works just fine. Based on the width being less than 700, it tells what the size is. But, imagine if I need the same screen size check in some other component. Should I copy-paste the code? I can! But that defeats the reusability of codes in React. Instead, we can extract this functionality inside a custom hook, and reuse it anywhere we want.



Creating the custom hook

Because the hooks are just JS Functions, they don’t need a React component to actually exist.
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;
Enter fullscreen mode

Exit fullscreen mode



Using the hook

We Extracted this functionality inside useWindowsWidth function. Now, we can import it anywhere we want to use it!

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

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

    return (
        //Return some element
    )
}
Enter fullscreen mode

Exit fullscreen mode

Now, wherever I need to know the size of the screen, I can use useWindowsWidth(). Isn’t this cool? Like, rather than writing entire code from scratch, you simply import the function. You can even make this code more dynamic using props by replacing the hard-coded screen size with this.props.screenSizeCheck and woosh! You can reuse the component wherever you want, with whatever size you want.



FAQ



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

Well, YES! According to the official React documentation:

Unlike a React component, a custom Hook doesn’t need to have a specific signature. We can decide what it takes as arguments, and what, if anything, it should return. In other words, it’s just like a normal function. Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it.



Do same custom hooks in two components share state?

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



We are Done!

Custom hooks allows you to really use your imagination when writing your React Code. You can extract and share logic in a way that was not possible with class components . And yes, this also enables us to make very ‘use’ful functions that can be used at different places in the application.
I wonder if you noticed the wordplay here.

Leave a Reply

Your email address will not be published.