Skip to content

React: Basic Fetch Hook

Data fetching is a common task in React applications. To avoid duplicating logic for handling loading and error states across multiple components, you can create a custom hook. The useFetch hook encapsulates the useEffect logic for fetching data from a given URL. It returns the data, a loading state, and any potential error, which you can then use in your components to render the UI accordingly. This pattern promotes code reuse and separation of concerns.

import { useState, useEffect } from 'react';

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

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

    return { data, loading, error };
}

1 Comment

Leave a Comment

Your email address will not be published.