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)