MyInternships.in

Data Fetching & APIs

React Custom useFetch Hook

A useFetch custom hook packages the data, loading, error and cleanup logic once and returns it to any component. It is the natural next step after writing the same effect for the third time.


What is Custom useFetch Hook in React?

A useFetch custom hook packages the data, loading, error and cleanup logic once and returns it to any component. It is the natural next step after writing the same effect for the third time.

Custom useFetch Hook example

A reusable fetching hook
JSX
export function useFetch(url, options) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!url) return;
    const controller = new AbortController();

    setLoading(true);
    fetch(url, { ...options, signal: controller.signal })
      .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then(json => { setData(json); setError(null); })
      .catch(err => { if (err.name !== 'AbortError') setError(err.message); })
      .finally(() => setLoading(false));

    return () => controller.abort();
  }, [url]);   // options intentionally excluded — see pitfalls

  return { data, loading, error };
}

// usage
const { data: jobs, loading, error } = useFetch('/api/jobs');

How this works

The hook returns an object rather than an array so callers can rename fields at the destructuring site, which matters when a component fetches from two endpoints.

Key points to remember

  • Guard on a falsy url so the hook can be called conditionally-in-effect for dependent requests.
  • A hand-rolled hook has no caching or deduplication — that is where TanStack Query earns its place.

Common mistakes with Custom useFetch Hook

  • Including options in the dependency array when callers pass an object literal, causing an infinite loop.
  • Reusing one hook instance and expecting two components to share the response — they each fetch separately.

React Custom useFetch Hook— Interview Questions & FAQs

Should I write my own useFetch or use a library?+

Write one to understand the mechanics. For production, TanStack Query or SWR add caching, deduplication, background refetching and retries that are genuinely hard to reimplement well.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships