Back to Snippets

React Hook For Asynchronous Data Fetching With Error Handling

JavaScript JavaScript / jQuery May 15, 2026

This React hook handles asynchronous data fetching from APIs, managing loading, error, and success states. It utilizes the useEffect and useCallback hooks to prevent infinite loops. A basic understanding of React hooks is required. The hook returns an object containing the fetched data, loading state, and any error that occurred.

Snippet Stats

Lines 36
Characters 1,061
Read 2 mins
javascript • 36 lines
/**
 * @param {string} url - The URL of the API endpoint to fetch data from
 * @param {object} options - Options for the fetch request
 * @return {object} An object containing the data, loading state, and error state
 * @throws {Error} If the fetch request fails
 */
import { useState, useEffect, useCallback } from 'react';

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

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

   useEffect(() => {
      fetchFunction();
   }, [fetchFunction]);

   return { data, loading, error };
};

export default useAsyncData;

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