Custom hooks

React.Js provides some hooks that are built-in which you can use in your React apps. But besides the already existing hooks, we can make our custom hook and use it in our apps resulting in a reduced amount of code and better readability. Custom hooks are normal JavaScript functions Usually, they start with the word “use” (important convention). and they may call other hooks(built-in or custom).


Why should we use Custom Hooks?

When there is a need to share logic between two JavaScript functions, we extract a new function. As hooks and components are functions, It works for them too.

Let’s assume while developing, there arises a need to use useEffect and useState. And we need to use the same logic combination of useEffect and useState again during further development.

Here we can duplicate the code, but we can reduce the repetitive code by using ReactJS Custom Hooks here.

Example:-

Often during development, there is a need to change the display according to the browser’s screen size.

Here, to make this happen we need to listen to the screen size changes and apply the changes accordingly.

For example, changing the display according to the device we are using like, Tablet, Mobile, or Laptop/Computer.

We might have to change the structure of the display or hide elements in certain cases. As this could be a repetitive operation, to code in a clean manner we create a useWindowResize to listen for changes in screen size.

import { useState, useEffect } from "react";

export const useWindowResize = () => {
  const [width, setWidth] = useState(window.innerWidth);
  const [height, setHeight] = useState(window.innerHeight);

  const listener = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
  };

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

  return {
    width,
    height,
  };
};


With this custom hook, we could enable our code to listen to any change in the size of the browsing window. And get the exact screen size accordingly (width and height).

Usage Example:-

const windowSize = useWindowResize();

if (window.Size.width <= mediumScreenSize) {
return(
        <div>Medium screen size components in display</div>
    )
}


Advantages of using Custom Hooks:-

  • Reusability - The hook we create can be used multiple times, without the need to write it again.
  • Clean Code - It provides a cleaner code base by extracting the component logic into a hook.
  • Maintainability - If there stands a need to change the logic of the hook. We just have to do it once.
  • Community Support - There is a high possibility that somebody has already created the hook we are looking for. There are already tons of Custom hooks available, which helps us to use them directly or modify them as per our needs.
Parv Saxena

Parv Saxena