TypeScript Generics in Custom React Hooks

In custom hooks, TypeScript generics allow you to define flexible data types at runtime, enabling a single hook to work with various data structures. Generics are ideal for hooks that perform similar operations on different types of data, like fetching various API data or managing states of diverse data models.

What Are Generics?

In TypeScript, generics are like placeholders for types, which let you define functions, classes, and hooks that work with any specified data type. When you create a custom hook, adding generics allows you to type-check the data it processes without tying it to a single data structure.

Example: Generic Data Fetching Hook

A common use case for custom hooks is data fetching. By using a generic type, we can create a flexible data-fetching hook that can be used for any API response.

Here, User is specified as the type for our useFetch hook, ensuring Users data conforms to an array of User objects.

import { useState, useEffect } from 'react';

type FetchState<T> = {
    data: T | null;
    loading: boolean;
    error: string | null;
};

function useFetch<T>(url: string): FetchState<T> {
    const [data, setData] = useState<T | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const result = await response.json();
                setData(result);
            } catch (err) {
                setError((err as Error).message);
            } finally {
                setLoading(false);
            }
        };
        fetchData();
    }, [url]);

    return { data, loading, error };
}

Conclusion

By using TypeScript generics in custom React hooks, you can achieve remarkable flexibility and type safety in your applications. With reusable hooks like useFetch, you can adapt to diverse data needs while keeping your code clean and well-typed.

Leave a comment

Your email address will not be published. Required fields are marked *