Custom Hooks : A Complete Guide

Custom Hooks : A Complete Guide

Custom Hook: An Introduction

Most of the react developers world have come across the term hooks while developing their products/projects. so, React hooks are functions that allow you to use the lifecycle methods from function components. There are in-built hooks also that are provided by react such as useState, useEffect and useContext.

A custom hook is a JavaScript function that starts with the keyword use. It can make use of react's in-built hooks. They return useful values for the components.

Note: It is not mandatory to use the keyword use but then react would not be able to identify the hook rules violation automatically.

Why Custom Hook?

As discussed earlier, the custom hook is a JavaScript function, and functions are usually used to extract the same repetitive piece of code. Hence, the Custom hook can be useful in state reusability that is if a state operation is occurring in multiple components. It also is useful in terms of readability. As custom hook approach provides cleaner logic and better understanding, making it easier to read. Whereas, when we use useState or other in-built hooks, it does not provide or convey meaning to the code of what's going to happen. For instance, if we have useToggle, it conveys the meaning that is going to be used for toggling purposes. Hence, it becomes easy to understand as well as predictable.

Now, let's try to implement our custom hook then.

Custom Hooks Examples

1. useToggle()

This is a very basic but very useful tool. It is used to toggle between states(true and false). The usage of this can be seen in modals and menus to close and open it. Let's just make one. Create a folder in any of your favorite editors and created a file with useToggle.js.

import { useState } from "react";

const useToggle = (initialState = false) => {
  const [state, setState] = useState(initialState);

  const toggle = () => {
    setState((prevState) => !prevState);
  };

  return [state, toggle];
};

export { useToggle };

useToggle() has its own state which is toggled using the toggle function. And its returns an array. This array has the existing state and toggle function. Now, this hook can be used in components to show/hide something.

Given below is an example of using useToggle() :

import { useToggle } from "../hooks/useToggle";

const TextOption = () => {
  const [isTextVisible, toggleText] = useToggle(false);
  return (
    <div>
      <button
        onClick={() => {
          toggleText();
        }}
      >
        {isTextVisible ? "Hide" : "Show"}
      </button>
      {isTextVisible ? (
        <div>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta,
          official
        </div>
      ) : null}
    </div>
  );
};

export { TextOption };

2. useCounter()

Now let's see an example of useCounter() where it will be able to increment/ decrement the count by 1. Similar to useToggle(), make a folder and create a file of useCounter.js and start coding the given code snippet.

import { useState } from "react";

const useCounter = (initialState = 0) => {
  const [count, setCount] = useState(initialState);

  const incrementCount = () => {
    setCount((count) => count + 1);
  };

  const decrementCount = () => {
    setCount((count) => count - 1);
  };

  return { count, incrementCount, decrementCount };
};

export { useCounter };

The above code is made to increment/ decrement by 1. You can make a few changes in the code to whatever number you want to increment/decrement.

2. useInput()

This is also one of the classic and easy examples of custom hooks. It's used to take the input value.

import { useState } from "react";

const useInput = (initialState) => {
  const [value, setValue] = useState(initialState);

  const handleChange = (e) => {
        setValue(e.target.value);
    };

    return {
        value,
        onChange: handleChange
    }
};

export { useInput };

Now, you can use your own custom input hook.

Conclusion

In this way, you can extract other hooks as well, there are many other examples such as onSubmit(), useFetch(), etc. However, do keep in mind to avoid early optimization of code and write an optimized version. It's better to first write the logic inside the component using in-built hooks and then think of extracting the hook.

That was all about custom hooks, hope you understood what they are and when are they used. Any feedbacks are appreciable.

Until next time, take care...bye👋