← Back to all snippets
JAVASCRIPT

Building a Custom useFetch Hook for API Calls

Create a reusable `useFetch` custom hook in React to encapsulate asynchronous API data fetching, efficiently handling loading, error states, and data with ease.

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        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]); // Re-run effect if URL changes

  return { data, loading, error };
}

// Example Usage:
// function UserProfile({ userId }) {
//   const { data, loading, error } = useFetch(`https://jsonplaceholder.typicode.com/users/${userId}`);

//   if (loading) return <div>Loading user...</div>;
//   if (error) return <div>Error: {error.message}</div>;
//   if (!data) return null;

//   return (
//     <div>
//       <h2>{data.name}</h2>
//       <p>Email: {data.email}</p>
//       <p>Phone: {data.phone}</p>
//     </div>
//   );
// }
How it works: This `useFetch` custom hook encapsulates the common logic for fetching data from an API. It manages three states: `data` for the fetched result, `loading` to indicate if the fetch is in progress, and `error` for any encountered issues. The `useEffect` hook triggers the asynchronous `fetchData` function when the component mounts or the `url` changes. It correctly handles network responses, JSON parsing, and error conditions, providing a clean interface to consume API data within any component.

Need help integrating this into your project?

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

Hire DigitalCodeLabs