Blog>
Snippets

Creating Custom Hooks for Data Fetching in Next.js 14

Build a custom hook for fetching data, encapsulating API call logic and state management, for reuse across components in Next.js.
import { useState, useEffect } from 'react';

// Custom hook for fetching data
export function useFetchData(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);
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
}
This is a custom hook named 'useFetchData' that takes a 'url' as an argument and returns an object containing 'data', 'loading', and 'error' state. It uses the 'useState' and 'useEffect' hooks from React to manage the state and side effects. The `fetchData` async function within the `useEffect` hook handles the logic of fetching the data from the API, updating the state accordingly, and catching any errors that may occur during the API call. The hook automatically re-fetches data when the 'url' changes.