JAVASCRIPT

Custom useFetch Hook for Asynchronous Data in React

Simplify data fetching in React components with this custom hook. Manages loading, error, and data states for API requests, making your fetch logic clean 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, options]);

  return { data, loading, error };
}
How it works: The `useFetch` hook encapsulates the logic for making an asynchronous data request. It maintains `data`, `loading`, and `error` states. When the `url` or `options` change, it re-fetches the data, updating the states accordingly. It uses `useEffect` to manage the side effect of fetching and includes error handling and proper loading state management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs