DEV Community

Andrew Lee
Andrew Lee

Posted on

 

Write your first React hook

It's possible to go far without writing our own hooks and instead lean on hooks made by third party libraries. However, we shouldn't shy away from it, at worst it will help us understand how other hooks work.

Let's write our own useFetch hook to clean up this component.

const SomeComponent = () => {
  const [data, setData] = useState(undefined);

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch("https://someurl.com");
      const data = await res.json();
      setData(data);
    };
    fetchData();
  }, []);

  return <pre>{data}</pre>;
}
Enter fullscreen mode Exit fullscreen mode

The first step to writing our hook is to pretend like it already works. How do we want the API to look like?

const { data } = useFetch("https://someurl.com");
Enter fullscreen mode Exit fullscreen mode

Now that we know how we want the end result to be, we can start filling in the details. One trick is to look for hooks (i.e. useState, useEffect) that can be grouped together, and put it inside a new hook.

In this case the useEffect is used with useState to set the data. This means we can group them together.

const useFetch = (url) => {
  const [data, setData] = useState(undefined);

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch(url);
      const json = await res.json();
      setData(json);
    };
    fetchData();
  }, []);

  return { data };
}
Enter fullscreen mode Exit fullscreen mode

Now we can use our new hook like this:

const SomeComponent = () => {
  const { data } = useFetch("https://someurl.com");

  return <pre>{data}</pre>;
}
Enter fullscreen mode Exit fullscreen mode

Writing our hooks is a great way to clean up our components and create bits of code that can easily be used in other components.

Top comments (0)

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React