How to create custom ReactJS hooks

Quite some time has passed since we introduced hooks in the codebase of our projects. Because of them, it has made the code reusable, cleaner, more readable and more satisfying to write.

Hooks present the future of development with ReactJs — that is for sure.

Other than the basic hooks provided by the library itself, you can also write your own little hook (or a big one)! Those kinds of hooks are named Custom hooks. Taken straight from the React docs — a custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.

In this little how-to, I will be showing how you can do just that! (…and with TypeScript too).

A state hook (counter custom hook)

In this example, I’ll show you how to implement a simple counter custom hook. Internally, it uses React’s useState and returns it along with a couple of other functions inside an object. The returned object is written with shorthand property names syntax.

const useCount = () => {
  const [count, setCount] = useState<number>(0);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);
  const increaseBy = (increaser: number) => setCount(count + increaser);
  const decreaseBy = (decreaser: number) => setCount(count + decreaser);

  return { count, increment, decrement, increaseBy, decreaseBy };
};

Now, this hook can be used anywhere within a function component. Here’s an example:

const { count, increment, decrement, increaseBy, decreaseBy } = useCount();
<div>
     <div>{count}</div>
     <button onClick={increment}>increment</button>
     <button onClick={decrement}>decrement</button>
     <button onClick={() => increaseBy(20)}>increase by 20</button>
     <button onClick={() => decreaseBy(20)}>decrease by 20</button>
</div>

A useEffect hook (custom fetch hook)

This example will show how you can use useEffect inside a custom hook. By using something like this, you could improve your fetch… or you can write a custom hook if you add a ton of event handlers!

const useFetch = (requestUrl: string) => {
  // set your fetch data and error types instead of any
  const [data, setData] = useState<any>(null);
  const [error, setError] = useState<any>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);

  React.useEffect(() => {
      const fetchData = async () => {
      setIsLoading(true);
      try {
          const response = await fetch(`${requestUrl}`);
          const json = await response.json();
          setData(json);
      } catch (err) {
          setError(err);
      }
      setIsLoading(false);
    };
  }, [requestUrl]);

  return { data, error, isLoading };
};

UseEffect custom hooks can be really viable and useful. Check out this useWhyDidYouUpdate hook, originally from Bruno Lemos.

Will you start using JS hooks?

As you can see from these small and compact examples, these hooks are plentifully useful. And the best thing about them is that they are super reusable even throughout different projects. If you create an awesome hook, you can use it in any future project!

On top of that, any hook desired, needed or thought of can be created. If you see a repeating pattern in your code which is using state or reacts to a certain event, you can easily put it in a custom hook.

Here are a couple of references to great hooks others have made, so check it out if you’re interested in learning more:
usehooks.com
Awesome React hooks