DeveloperBreeze

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.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

State Management Beyond Redux: Using Zustand for Scalable React Apps

You can persist state to localStorage or sessionStorage:

import create from 'zustand';
import { persist } from 'zustand/middleware';

const useStore = create(persist(
  (set) => ({
    count: 0,
    increase: () => set((state) => ({ count: state.count + 1 })),
  }),
  {
    name: 'counter-storage',
  }
));

May 03, 2025
Read More
Article

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

As web apps grow in complexity, the micro frontends approach is gaining traction. This pattern involves splitting a large frontend app into smaller, more manageable pieces, each developed by independent teams. Benefits include:

  • Scalability: Smaller teams can work on individual components without stepping on each other’s toes.
  • Flexibility: Mix and match technologies based on project needs.
  • Easier Maintenance: Isolated components make debugging and updating less daunting.

Feb 11, 2025
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • 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.

JavaScript isn't limited to the browser anymore. It's being used in diverse domains:

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
Tutorial
php

Handling HTTP Requests and Raw Responses in Laravel

In this tutorial, we covered how to handle various HTTP requests in Laravel using the Http facade, including:

Laravel’s Http facade provides a simple yet powerful way to work with APIs, making HTTP requests and handling responses intuitive and clean. By utilizing the methods discussed, you can seamlessly integrate external services into your Laravel application.

Oct 24, 2024
Read More
Article

Integrating Flowbite with Tailwind CSS: A Step-by-Step Tutorial

To ensure that Tailwind CSS recognizes Flowbite's components and styles, you need to configure your tailwind.config.js appropriately.

Ensure your tailwind.config.js includes Flowbite's plugin and content paths as shown earlier. Here's the complete configuration for reference:

Oct 24, 2024
Read More
Article
javascript

20 Useful Node.js tips to improve your Node.js development skills:

No preview available for this content.

Oct 24, 2024
Read More
Tutorial
javascript

AJAX with JavaScript: A Practical Guide

Before the Fetch API, the traditional way to make AJAX requests was using XMLHttpRequest.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX with XMLHttpRequest</title>
</head>
<body>
    <button id="fetchDataBtn">Fetch Data</button>
    <div id="dataOutput"></div>

    <script>
        document.getElementById('fetchDataBtn').addEventListener('click', function() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);

            xhr.onload = function() {
                if (this.status === 200) {
                    var data = JSON.parse(this.responseText);
                    document.getElementById('dataOutput').innerHTML = `
                        <h3>${data.title}</h3>
                        <p>${data.body}</p>
                    `;
                }
            };

            xhr.onerror = function() {
                console.error('Request failed.');
            };

            xhr.send();
        });
    </script>
</body>
</html>

Sep 18, 2024
Read More
Tutorial
css

CSS Variables and Custom Properties: Dynamic Theming and Beyond

:root {
    --primary-color: #3498db;
}

.header {
    --primary-color: #e74c3c; /* Overriding the global primary color */
}

h1 {
    color: var(--primary-color); /* Uses the header's primary color inside .header */
}

In this example, the --primary-color is overridden within the .header class, so all elements inside .header will use the new color.

Sep 05, 2024
Read More
Tutorial
javascript

Advanced JavaScript Tutorial for Experienced Developers

In this example, even though setTimeout is set to 0 milliseconds, the callback is not executed until the main call stack is clear, resulting in "Timeout" being logged last.

Asynchronous programming is essential for creating responsive web applications. Promises and async/await simplify working with asynchronous operations, while understanding the Event Loop helps you write more efficient code.

Sep 02, 2024
Read More
Tutorial
javascript

Getting Started with Axios in JavaScript

  • Experiment with making requests to different APIs.
  • Explore more advanced Axios features like interceptors and request cancellation.
  • Consider using Axios in a framework like React or Vue.js for even more powerful applications.

Sep 02, 2024
Read More
Tutorial
javascript

Creating a Component Library with Storybook and React

Building a component library is an essential step for any organization or project that values reusability and consistency in UI development. By creating a centralized library, you can streamline development, maintain design consistency, and speed up the process of building new features. In this tutorial, we'll guide you through the process of setting up a component library using React and Storybook, a powerful tool for developing and documenting UI components in isolation.

Before we start, ensure you have the following:

Aug 27, 2024
Read More
Cheatsheet
solidity

Solidity Cheatsheet

  • Limit gas consumption by optimizing functions.

  • Write unit tests for every contract function.

Aug 22, 2024
Read More
Cheatsheet

Comprehensive React Libraries Cheatsheet

This cheatsheet offers a broad overview of the most widely-used libraries in the React ecosystem. These libraries cover various aspects of React development, from state management and UI components to testing and animations, helping you build robust and maintainable applications. Whether you're a beginner or an experienced developer, integrating these tools into your workflow can significantly enhance your productivity and the quality of your React projects.

Aug 21, 2024
Read More
Cheatsheet
javascript css +1

Building a Chrome Extension: A Step-by-Step Tutorial

To test your extension:

  • Use chrome://extensions/ to inspect your extension and check for any errors.
  • Use Chrome DevTools to debug your extension's popup and content scripts.

Aug 20, 2024
Read More
Cheatsheet
javascript

React Performance Optimization Cheatsheet: Hooks, Memoization, and Lazy Loading

import React, { useMemo } from 'react';

function ExpensiveCalculationComponent({ number }) {
  const squaredNumber = useMemo(() => {
    console.log('Calculating...');
    return number * number;
  }, [number]);

  return <div>The square of {number} is {squaredNumber}</div>;
}

In this example, the square of the number is only recalculated when number changes, avoiding unnecessary computations.

Aug 20, 2024
Read More
Tutorial
bash

Creating and Managing Bash Scripts for Automation

Cron is a time-based job scheduler in Unix-like systems that allows you to automate script execution.

   crontab -e

Aug 19, 2024
Read More
Tutorial
javascript php

Integrating Laravel and React with Vite: Using Databases and PHP in a Full-Stack Project

React will interact with Laravel’s backend through API endpoints. We'll create a controller and define routes for CRUD operations.

Generate a controller to handle the logic for your Post model:

Aug 14, 2024
Read More
Tutorial

Integrating Vite with Laravel for Modern Web Development

The @vite directive ensures that the correct files are included during development and production, automatically handling versioning and cache busting.

Vite provides HMR out of the box, allowing your changes to reflect instantly without a full page reload. When the development server is running, Vite automatically injects the updated modules.

Aug 14, 2024
Read More
Tutorial

Getting Started with Vite: A Fast Frontend Build Tool

If you selected React during the setup, your project is already configured with React. You can start building React components directly.

Here's a simple example of a React component:

Aug 14, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!