DeveloperBreeze

Usestate Development Tutorials, Guides & Insights

Unlock 1+ expert-curated usestate tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your usestate skills on DeveloperBreeze.

React Custom Hook for API Requests

Code August 12, 2024
javascript

import { useState, useEffect } from 'react';

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

    useEffect(() => {
        let isMounted = true; // Track if component is mounted

        const fetchData = async () => {
            setLoading(true);
            try {
                const response = await fetch(url, options);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const result = await response.json();
                if (isMounted) {
                    setData(result);
                }
            } catch (error) {
                if (isMounted) {
                    setError(error);
                }
            } finally {
                if (isMounted) {
                    setLoading(false);
                }
            }
        };

        fetchData();

        return () => {
            isMounted = false; // Cleanup to avoid setting state on unmounted component
        };
    }, [url, options]);

    return { data, loading, error };
}

export default useFetch;

Here’s an example of how to use the useFetch hook in a React component to fetch and display data.