Episode 20 of 32

Making a Custom Hook

Create a reusable custom hook to encapsulate the fetch logic.

Custom hooks let you extract and reuse logic across components.

The useFetch Hook

// useFetch.js
import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [isPending, setIsPending] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch(url)
      .then(res => {
        if (!res.ok) throw Error("Could not fetch");
        return res.json();
      })
      .then(data => {
        setData(data);
        setIsPending(false);
        setError(null);
      })
      .catch(err => {
        setIsPending(false);
        setError(err.message);
      });
  }, [url]);

  return { data, isPending, error };
};

export default useFetch;

Using the Hook

const { data: blogs, isPending, error } = useFetch("http://localhost:8000/blogs");