DEV Community

Cover image for Create your custom hook
Tiberius Mairura
Tiberius Mairura

Posted on

Create your custom hook

Hooks are one of the most significant features that make React such an awesome library to work with. Hooks have not been always in React but are a feature that came with react 16.8 to allow function-based components to access state and other useful react features that are otherwise only available in class components.

In a layman's language, a react hook is a javascript function. However, they are a special kind of functions because they impose a few rules on top i.e

  • They can only be called at the top level

  • They cannot be called inside loops, conditions, or nested functions

There is quite a number of hooks as of now which can accomplish most of the tasks you will need to accomplish in your UI.

However, we all know well enough that there will always be those special use cases that do not have a ready-made solution and we could like to implement ours.

Imagine a situation where your react UI consumes data from an API. In such a case, you will have an implementation similar to this:

import React from "react";

function Test() {
  const [data, setData] = useState(null);
  useEffect(() => {
    async function getData() {
      try {
        const response = await fetch(url);
        const data = response.json();
        setData(data);
      } catch (error) {
        console.log(error);
      }
    }
    getData();
  }, []);

  return (
    <div>
      <ul>{data && data.map((d) => <li key={d.id}>{d}</li>)}</ul>
    </div>
  );
}

export default Test;
Enter fullscreen mode Exit fullscreen mode

The snippet above uses react's useEffect hook to invoke a function that makes a network request that fetches data when the component mounts for the first time.

If we want to fetch data again in a different component, we will re-write similar code as above. Assume you have 10 components that make such calls. This means that you will have 10 duplicates of that code, outrightly violating the beloved DRY principle.

Being generous enough, react offers us a way to craft our hooks to satisfy our unique needs. Thus we can build a custom hook that we can reuse across all our components and revive our DRY principle.

Let us create one!

import React from "react";

function useFetch(url) {
  const [data, setData] = useState(null);
  useEffect(() => {
    async function getData() {
      try {
        const response = await fetch(url);
        const data = await response.json();
        setData(data);
      } catch (error) {
        console.log(error);
      }
    }
    getData();
  }, []);

  return data;
}

export default useFetch;
Enter fullscreen mode Exit fullscreen mode

Great!

Now, all we need to do is import our custom hook and use it whenever we want.

import React from 'react'

import useFetch from './useFetch'
function Test() {
const data = useFetch(URL)
return (
    <div>
      <ul>{data && data.map((d) => <li key={d.id}>{d}</li>)}</ul>
    </div>
  );
}

export default Test
Enter fullscreen mode Exit fullscreen mode

One thing to note is that custom hooks will obey the same rules (see above) as the inbuilt hooks only if you follow certain rules when creating them.

Well, the good news is, it is not difficult to follow them. The most important one is that the name of the custom hook must start with use and follow the cameCaseStyle.

Key Takeaways

  • React hooks are simply JavaScript functions

  • Hooks allow functional components to access state and other react features

  • We can build our custom hooks and reuse them whenever we want

  • For custom hooks to follow the same rules as the in-built ones, we have to name them properly by starting the name with use and use cameCase

Top comments (0)