Published on August 12, 2024By DeveloperBreeze

React Custom Hook for API Requests

This snippet provides a custom hook to manage the lifecycle of API requests in a React application, offering a clean and reusable way to handle data fetching.

Custom Hook: useFetch

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;

Using the Custom Hook

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

import React from 'react';
import useFetch from './useFetch'; // Ensure correct import path

function UserList() {
    const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');

    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error: {error.message}</p>;

    return (
        <ul>
            {data.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

export default UserList;

Features and Benefits

  • Reusability: The useFetch hook can be used across different components and applications, reducing code duplication and simplifying API interaction.

  • Loading and Error States: Automatically manages loading and error states, providing a consistent way to handle asynchronous operations.

  • Cleanup Handling: Prevents state updates on unmounted components, reducing potential memory leaks and ensuring stability.

Customization and Extension

  • Custom Headers: Extend the hook to accept custom headers or authentication tokens in the options parameter.

  • Polling: Implement a polling mechanism by setting up a setInterval within the useEffect for periodically fetching data.

  • Data Transformation: Add a callback function to transform the fetched data before setting it in state.

Comments

Please log in to leave a comment.

Continue Reading:

File Upload

Published on January 26, 2024

php

Asynchronous Data Fetching in JavaScript using 'fetch'

Published on January 26, 2024

javascript

Asynchronous Fetch in JavaScript using async/await

Published on January 26, 2024

javascript

JavaScript File Upload using Fetch API and FormData

Published on January 26, 2024

javascript

Fetch JSON Data from API in JavaScript

Published on January 26, 2024

javascript

JavaScript Promise Example

Published on January 26, 2024

php

Fetching Chuck Norris Jokes from API in JavaScript

Published on January 26, 2024

javascript

Tailwind Browser Mockup

Published on January 26, 2024

Simple and Clean Tailwind Buttons

Published on January 26, 2024