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

const count = useStore((state) => state.count);

By selecting only the necessary state slices, you can optimize component rendering and improve performance.

May 03, 2025
Read More
Article

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

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.

Whether you’re following our step-by-step tutorials or exploring the latest tech trends, remember that the world of web development is vast and full of opportunities. Keep learning, keep experimenting, and most importantly, have fun creating amazing digital experiences.

Feb 11, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • Tools like React Native enable building native apps using JavaScript.
  • Example: Facebook's mobile app.
  • Frameworks like Electron allow creating cross-platform desktop apps.
  • Example: Visual Studio Code.

Dec 10, 2024
Read More
Code
javascript

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

  • serverSide: true enables server-side pagination, sorting, and filtering.
  • processing: true displays a processing indicator while fetching data.
  • The ajax object defines how data is fetched from the server.
  • url: Endpoint for fetching data.
  • type: HTTP method (GET).
  • error: Logs errors that occur during the AJAX request.
  • dataSrc: Processes the server's response. It logs the data and returns records for display.

Oct 24, 2024
Read More

Discussion 0

Please sign in to join the discussion.

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