← Back to all snippets
JAVASCRIPT

Reusable API Data Fetching with a Custom React Hook

Create a custom React hook to encapsulate asynchronous data fetching logic, providing loading, error, and data states for any API endpoint.

import React, { useState, useEffect } from 'react';

// Custom Hook for fetching data
const useFetch = (url) => {
  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);
        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 Component using the custom hook
function DataDisplay() {
  const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/posts/1');

  if (loading) return <p>Loading data...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div style={{ border: '1px solid #ddd', padding: '15px', borderRadius: '8px' }}>
      <h2>Fetched Data:</h2>
      <p><strong>Title:</strong> {data?.title}</p>
      <p><strong>Body:</strong> {data?.body}</p>
    </div>
  );
}
How it works: Custom hooks allow you to extract and reuse stateful logic across multiple components. This `useFetch` custom hook encapsulates the common pattern of fetching data from an API. It uses `useState` to manage the `data`, `loading`, and `error` states and `useEffect` to perform the asynchronous fetch operation when the component mounts or when the `url` dependency changes. This makes API consumption clean and reusable, as any component can simply call `const { data, loading, error } = useFetch(myApiUrl)` to get its data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs