Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 60

Building a Custom `useFetch` Hook

Recommended resources

Hello! Welcome to the fourth lesson in our module on custom hooks.

In our last session, you learned how to create a generic, type-safe custom hook, useLocalStorage, using TypeScript. The key takeaway was the power of encapsulating stateful logic (useState + useEffect) into a single, reusable function. This pattern of identifying duplication, extracting logic, and generalizing with parameters and generics is fundamental to writing clean, professional React code.

Today, we're going to apply that exact pattern to one of the most common tasks in any web application: fetching data from an API. Repetitive data-fetching code clutters components and is prone to errors. Our goal is to extract this data fetching, loading, and error handling logic into a custom useFetch hook. This is a hook you'll find yourself reaching for in almost every project.

The Problem: Repetitive Data Fetching

Imagine you need to fetch data in a component. You'd typically need:

  1. A state for the data itself (e.g., useState<User | null>(null)).
  2. A state to track if the request is in progress (useState<boolean>(true)).
  3. A state to hold any potential errors (useState<Error | null>(null)).
  4. A useEffect hook to perform the fetch operation when the component mounts.

If you need to fetch data in another component, you write the same combination of useState and useEffect all over again. This is a classic violation of the DRY (Don't Repeat Yourself) principle.

This article provides a great summary of this exact problem and the pattern it creates.

Creating React custom hooks with Pieces

The article 'Creating React custom hooks with Pieces' clearly illustrates the problem. Pay attention to the initial code block showing how useState and useEffect are used together for a simple fetch.

Read the section 'Creating a custom data fetching hook'. Focus on the first code block that shows the typical, repetitive logic inside a component. Notice how it sets up three state variables and uses a useEffect to manage the fetch lifecycle.

As you can see, this logic is entirely self-contained and doesn't depend on the component's specific UI. This makes it a perfect candidate for a custom hook.


Building a useFetch Hook: A Step-by-Step Approach

We will build our hook incrementally, starting with the basics and progressively adding features to make it robust and production-ready. This test-driven development style, common in software engineering, ensures we address each requirement systematically.

Step 1: Handling Loading and Data States

First, our hook needs to manage the loading state and store the data that comes back from the API. We'll use useState for this. Since we want our hook to be versatile, we'll use a TypeScript generic <T> to represent the type of the data being fetched.

The following video demonstrates how to implement this basic functionality.

Build react useFetch from scratch | with check list, tests and examples

The video 'Build react useFetch from scratch' from the Syntax channel provides an excellent, detailed walkthrough. We'll start by watching how to implement the core fetching and state management.

Watch from 05:55 to 07:14 and then from 09:19 to 10:39. The first segment (05:55-07:14) covers setting up the initial useEffect to fetch on mount and managing the loading state. The second segment (09:19-10:39) shows how to add a data state and, crucially, how to use the generic type <T> to make the hook type-safe.

Step 2: Robust Error Handling

Network requests can fail for many reasons (e.g., server is down, bad URL, parsing error). A good fetch hook must gracefully handle these errors. We can achieve this by wrapping our fetch logic in a try...catch block.

Build react useFetch from scratch | with check list, tests and examples

Let's continue with the same video to see how to properly implement error handling.

Watch from 16:06 to 19:45. This section is key. It demonstrates how to add an error state and use a try...catch block to handle both network errors (from fetch itself) and JSON parsing errors. Note how the error object is handled in a type-safe way.

At this point, we have a basic useFetch hook that handles the three core states: data, loading, and error.

React Component Using a Custom `useJsonFetch` Hook
A React component using a custom `useJsonFetch` hook. This demonstrates the clean interface we are aiming for, where the component simply destructures `data`, `error`, and `loading` from the hook and uses them to render the UI.

Making the Hook Production-Ready: Handling Edge Cases

Our hook works, but it's not yet robust. What happens if the component unmounts before the fetch completes? Or if we need to refetch the data based on user interaction?

The Problem of Race Conditions and Cleanup

If a user navigates away from a page while a data fetch is in progress, the component will unmount. When the fetch eventually completes, it will try to call setData on an unmounted component. This is a memory leak and a common source of bugs in React.

The solution is the AbortController API. This browser API allows you to create a signal that can be used to abort web requests. We can create an AbortController when a fetch begins and call its abort() method in the useEffect cleanup function, which runs when the component unmounts.

Furthermore, if a user triggers a refetch while a previous one is still in flight (e.g., typing quickly in a search box), you can get a race condition where the older request resolves after the newer one, showing stale data. The AbortController solves this too: before starting a new request, we abort the previous one.

Because the AbortController instance needs to persist across re-renders without triggering them, we'll store it in a useRef.

This concept is critical for building reliable applications. The next video segment provides one of the clearest explanations available.

Build react useFetch from scratch | with check list, tests and examples

This is the most advanced and important part of our lesson. Watch carefully how AbortController and useRef are combined to handle race conditions and cleanup.

Watch from 21:18 to 29:51. This is a dense but incredibly valuable section. Focus on: How an AbortController is created and stored in a useRef. How the controller's signal is passed to the fetch call. How the previous request is aborted (controller.current.abort()) before a new one starts. How the useEffect cleanup function is used to abort the request on unmount.


The Complete useFetch Hook

Let's assemble everything we've learned into a single, robust useFetch hook. This implementation combines generic types, state management for data, loading, and error, and a cleanup mechanism using AbortController. We'll also extract the fetch logic into a useCallback and return it as a refetch function, allowing for manual re-triggering.

// src/hooks/useFetch.ts

import { useState, useEffect, useRef, useCallback } from 'react';

// Define the shape of the options object for our hook
interface UseFetchOptions extends RequestInit {
  autoInvoke?: boolean;
}

// Define the shape of the returned object
interface UseFetchReturn<T> {
  data: T | null;
  loading: boolean;
  error: Error | null;
  refetch: () => Promise<T | void>;
}

export function useFetch<T>(
  url: string,
  options: UseFetchOptions = { autoInvoke: true }
): UseFetchReturn<T> {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(options.autoInvoke || false);
  const [error, setError] = useState<Error | null>(null);

  // Use a ref to hold the AbortController
  // This persists across renders without causing re-renders itself
  const controller = useRef<AbortController | null>(null);

  const { autoInvoke, ...fetchOptions } = options;

  const refetch = useCallback(async () => {
    // If a previous request is in flight, abort it
    if (controller.current) {
      controller.current.abort();
    }

    // Create a new AbortController for the new request
    controller.current = new AbortController();
    setLoading(true);
    setError(null);

    try {
      const response = await fetch(url, {
        ...fetchOptions,
        signal: controller.current.signal,
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const responseData = (await response.json()) as T;
      setData(responseData);
      return responseData;
    } catch (err: any) {
      // AbortError is expected when we cancel a request, so we don't treat it as a real error.
      if (err.name !== 'AbortError') {
        setError(err);
      }
    } finally {
      setLoading(false);
    }
  }, [url]); // `fetchOptions` is not included as it can cause infinite loops if it's an object literal.
               // For a production hook, you'd use use-deep-compare-effect or manage options via state.

  useEffect(() => {
    if (autoInvoke) {
      refetch();
    }

    // The cleanup function runs on unmount or before the effect re-runs.
    return () => {
      if (controller.current) {
        controller.current.abort();
      }
    };
  }, [refetch, autoInvoke]);

  return { data, loading, error, refetch };
}
Test your understanding!

Our useFetch hook is great, but what if a component wants to be notified when a fetch successfully completes to perform another action (e.g., show a toast notification)?

Modify the useFetch hook to accept an optional onSuccess callback function in its options parameter. This function should be called with the fetched data only when the request is successful.

Show answer

First, you would update the UseFetchOptions interface and the hook's signature to accept the callback:

interface UseFetchOptions<T> extends RequestInit {
  autoInvoke?: boolean;
  onSuccess?: (data: T) => void; // Add the callback here
}

export function useFetch<T>(
  url: string,
  options: UseFetchOptions<T> = { autoInvoke: true }
): UseFetchReturn<T> {
  // ...
  const { autoInvoke, onSuccess, ...fetchOptions } = options;
  // ...
}

Note that UseFetchOptions now needs to be generic to type the onSuccess data parameter correctly.

Then, inside the refetch function's try block, you would call onSuccess after successfully setting the state.

// Inside the refetch's try block
// ...
const responseData = (await response.json()) as T;
setData(responseData);

// Call the callback if it was provided
if (onSuccess) {
  onSuccess(responseData);
}

return responseData;
// ...

This change makes the hook even more flexible by allowing components to react to successful data fetching without needing a useEffect to watch the data state.


Conclusion

You have now successfully built a production-grade useFetch hook. By abstracting this logic, you've made your components cleaner, more declarative, and less prone to common bugs like race conditions and memory leaks.

Key Takeaways:

  • Encapsulation is Key: Data fetching involves managing multiple states (data, loading, error) and effects. A custom hook is the perfect way to encapsulate this complex, stateful logic.
  • Generics Provide Type Safety: Using <T> allows your useFetch hook to work with any API response shape while giving you full TypeScript support.
  • Cleanup is Not Optional: Using AbortController with useEffect's cleanup function and useRef is a critical pattern for preventing memory leaks and race conditions in asynchronous operations.
  • Expose Control: Returning a refetch function from your hook gives the consuming component control over when to re-trigger the data fetch, enabling interactive experiences.

Preview of the Next Lesson:
We will continue building on this theme of encapsulating common logic. Next, we will tackle another ubiquitous feature: forms. You will build a custom useForm hook to manage the state and handlers for form inputs, further simplifying your component code and centralizing form management logic.