DeveloperBreeze

React Custom Hook for API Requests

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.

Related Posts

More content you might like

Tutorial

State Management Beyond Redux: Using Zustand for Scalable React Apps

While Redux remains a powerful tool for state management, there are scenarios where Zustand might be a better fit:

  • Project Size: For small to medium-sized projects, Zustand's simplicity can accelerate development.
  • Team Experience: Teams new to state management may find Zustand's learning curve more approachable.
  • Boilerplate Reduction: If minimizing boilerplate is a priority, Zustand offers a cleaner setup.
  • Performance Needs: Zustand's selective rendering can enhance performance in applications with frequent state updates.

May 03, 2025
Read More
Article

Mastering Modern Web Development: Trends, Tools, and Tutorials for 2025 and Beyond

Detailed tutorials for each step can be found on our website, complete with code snippets and troubleshooting tips!

Web development in 2025 is all about creating fast, scalable, and user-friendly applications. Embracing trends like Jamstack, micro frontends, and AI integration will keep you ahead of the curve. By mastering modern tools like Next.js, Tailwind CSS, Docker, and Kubernetes, you’re not just building websites—you’re shaping the future of digital experiences.

Feb 11, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • Frameworks and libraries like React, Angular, and Vue.js make it easier to build Single Page Applications (SPAs).
  • Examples: Gmail, Netflix, Trello.
  • With Node.js, JavaScript powers the back-end to handle databases, APIs, and server logic.
  • Examples: REST APIs, real-time collaboration tools like Google Docs.

Dec 10, 2024
Read More
Code
javascript

Dynamic and Responsive DataTable with Server-Side Processing and Custom Styling

No preview available for this content.

Oct 24, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!