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

JavaScript
This React code snippet utilizes memoization to enhance performance by minimizing unnecessary re-renders, particularly useful in scenarios involving c...

Optimizing React Components With Memoization And Error Handling

JavaScript
This React pattern utilizes memoization to optimize rendering by preventing unnecessary re-renders of components. It is particularly useful when worki...

React Optimization Technique Using Memoization for Improved Rendering Performance