JAVASCRIPT

Custom React Hook for Data Fetching with Loading and Error States

Implement a custom React hook, `useFetch`, to handle asynchronous data fetching, including managing loading and error states, making API calls cleaner and reusable.

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(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(url, options);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url, JSON.stringify(options)]); // Re-fetch if URL or options change

  return { data, loading, error };
}

// Example Usage:
// function MyComponent() {
//   const { data, loading, error } = useFetch('https://api.example.com/data');

//   if (loading) return <div>Loading...</div>;
//   if (error) return <div>Error: {error.message}</div>;
//   return <div>Data: {JSON.stringify(data)}</div>;
// }
How it works: This `useFetch` hook simplifies data fetching in React components. It manages three states: `data` for the fetched result, `loading` to indicate an ongoing request, and `error` for any network or API issues. The `useEffect` hook triggers the data fetch when the `url` or `options` change. It provides a clean, reusable interface to integrate asynchronous data operations into any functional component, reducing boilerplate code and improving readability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs