DEV Community

Cover image for Creating Custom Hooks with React.js
Kuvam Bhardwaj
Kuvam Bhardwaj

Posted on • Updated on

Creating Custom Hooks with React.js

Introduction

Hooks were introduced quite a while ago in React. They enabled to tap into state & lifecycle methods WITHOUT using class components.

In this post I will be showing you with the help of a common problem, how can you create a hook for your own. Let's Get Started 🚀

Problem

So let's suppose we're making a web app where we need to render different components depending upon the screen width of the user.

So we wrote this code to solve it:

arbitrary code to solve window screen width problem

It will work fine. Missing one crucial case, What if the user switches to landscape mode on its mobile? The site will still be showing the mobile screen component instead of showing the desktop or bigger screen component.

Of course, this problem can be solved with CSS & rather with 2-3 words with tailwind.
The thing is, I want to show you another way of solving this problem The Reactive way!

Creating the Hook Component

useWindowWidth custom react hook

What just happened?

Here, if you look at the useWindowWidth function, you'll notice that it's just a normal function that also happens to use other built-in hooks like useState & useEffect.

What this function does is, it declares a state variable in its scope with useState calling it width & its setter setWidth and throws in the value of window.screen.width as its initial state.

Then, we call the useEffect hook and add an event listener for the 'resize' event firing off a function that sets the value of width whenever the browser window is resized.

If you look closely at the useEffect hook, you'll see an empty array which is there to indicate that this useEffect does not depend on any external value meaning that it will ONLY RUN ONCE even in occasional re-renders. This array is also called the DEPENDENCY ARRAY of the useEffect hook.

Next, we return the width value as the output of this function. Next time the browser window is resized, it will return a new value of width representing the window's current screen width. And we know that whenever we associate useState to a variable, it causes a re-render in every location where the variable was referenced.

This is how it is working now:
working of custom hooks

For those of you thinking:

" Hey! but why we prefixed 'use' with the function's name in useWindowWidth? "

This is a text I extracted from the official documentation of React.js on custom hooks, have a look:

Do I have to name my custom Hooks starting with “use”? Please do. This convention is very important. Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it.

Outro

The use of custom hooks is not limited to just this use case, you can apply it pretty much anywhere you like from auto-login functions to UI-related parts. Even making queries to the server on regular basis, that helps deliver a near-real-time experience to the end user. Possibilities are, as always, ENDLESS.

So, that's all for today folks! hope you found it helpful :)


If you like my posts, consider following :)

Twitter -> @BhardwajKuvam

Github -> @kuvamdazeus

LinkedIn -> @kuvambhardwaj

Portfolio -> kuvambhardwaj.vercel.app

Top comments (2)

Collapse
 
link2twenty profile image
Andrew Bone

Hi, this a nice way to keep track of the screen size though I would add it's important to remove event listeners when you detach the hook. You'd do that by having a return in your useEffect.

import { useEffect, useState } from "react";

export useWindowWidth() {
    const [width, setWidth] = useState(window.screen.width);

    useEffect(() => {
        const updateWidth = () => setWidth(window.screen.width);
        window.addEventListener('resize', updateWidth);
        return () => window.removeEventListener('resize', updateWidth);
    },[]);

    return width;
}
Enter fullscreen mode Exit fullscreen mode

Also it might be worth looking at matchMedia as that will allow you to do more things.

Collapse
 
kuvambhardwaj profile image
Kuvam Bhardwaj

Thanks for pointing that out, quite an important one, left that my bad