Back to Snippets

React Hook For Asynchronous Data Fetching With Error Handling And Loading States

JavaScript JavaScript / jQuery June 15, 2026

This React hook handles asynchronous data fetching with error handling and loading states, making it useful for fetching data from APIs. It utilizes React hooks and includes proper error handling and loading states. The hook is designed to be reusable and provides a simple way to fetch data from an API. It returns an object with the fetched data, error, and loading state.

Snippet Stats

Lines 38
Characters 1,280
Read 2 mins
javascript • 38 lines
/**
       * Fetches data from an API and handles errors.
       * 
       * @param {string} url The URL of the API endpoint.
       * @param {object} options Options for the fetch request.
       * @returns {Promise<object>} A promise that resolves with the fetched data.
       * @throws {Error} If the fetch request fails.
       */
      import { useState, useEffect } from 'react';

      const useFetchData = (url, options) => {
         const [data, setData] = useState(null);
         const [error, setError] = useState(null);
         const [loading, setLoading] = useState(false);

         useEffect(() => {
            const fetchData = async () => {
               setLoading(true);
               try {
                  const response = await fetch(url, options);
                  if (!response.ok) {
                     throw new Error(response.statusText);
                  }
                  const data = await response.json();
                  setData(data);
               } catch (error) {
                  setError(error);
               } finally {
                  setLoading(false);
               }
            };
            fetchData();
         }, [url, options]);

         return { data, error, loading };
      };

      export default useFetchData;

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
JavaScript
This React pattern optimizes performance in functional components by preventing unnecessary re-renders using the useMemo and useCallback hooks. It is ...

React Performance Optimization Using useMemo And useCallback Hooks

JavaScript
This React code snippet utilizes the Context API along with the useMemo hook to optimize performance by sharing data between components efficiently. I...

Optimizing React Performance With Context API And useMemo

JavaScript
This code snippet demonstrates how to optimize React hooks using useCallback and useMemo to prevent unnecessary re-renders and improve performance. It...

React Performance Optimization Using UseCallback And UseMemo Hooks