Building Custom Hooks in React: useFetch & useAxios

2023-01-05

...

Introduction

Creating custom Hooks in React is a great way to extend the functionality of existing components. Hooks are a powerful tool that allows developers to create reusable logic and can be used to write cleaner and more concise code. We will learn how to create custom Hooks and provide practical examples.

Creating Custom Hooks

Creating custom Hooks in React is relatively easy and can be done in just a few steps. First, create a function that contains the logic for the hook. This function should be passed in the component’s props and should return the desired information. This function can also be used to provide additional parameters to the hook. Next, the hook should be registered by calling the React.useHook() function. Finally, the hook should be used in the component by calling the hook with the desired parameters.

useFetch / useAxios Custom Hook

Now that we have discussed the basics of creating custom hooks in React, let’s look at a practical example that fetches data from an API. First, create a function called useFetch. It would be better to name our custom hooks with use[….]. Always make it readable.

import { useEffect, useState } from "react";

export default function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data))
      .catch((error) => setError(error))
      .finally(() => {
        setLoading(false);
      });
  }, [url]);
  return { data, loading, error };
}

or if you want to use Axios, the same logic works for Axios, too!

import { useEffect, useState } from "react";
import axios from "axios";

function useAxios(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading(true);
    axios
      .get(url)
      .then((res) => setData(res.data))
      .catch((err) => setError(err))
      .finally(() => setLoading(false));
  }, [url]);

  return { data, loading, error };
}

export default useAxios;

It is that much easy, folks! Let’s use GitHub API and see our custom hook in action.

First I have created a component to show our data such as a GitHub repo card. It is pretty basic.

const RepoCard = ({ url, title, desc, type, pushed_at }) => {
  return (
    <>
      <div>
        <div>
          <a href={url}>{title}</a>
          <p>{desc}</p>
        </div>
        <div>
          <span>{type}</span>
          <span>{pushed_at}</span>
        </div>
      </div>
    </>
  );
};

export default RepoCard;

That much easy to build reusable custom hooks in React.

Conclusion

Creating custom Hooks in React is a great way to extend the functionality of existing components. Custom Hooks allow developers to create reusable logic, and can be used to write cleaner and more concise code.