Frontend Blocks typescript Intermediate

useFetch Hook with Abort

Data fetching hook with loading/error state and automatic request cancellation on unmount.

typescript
import { useState, useEffect } from 'react';
export function useFetch(url) {
  const [data, setData]    = useState(null);
  const [loading, setLoad] = useState(true);
  const [error, setError]  = useState(null);
  useEffect(() => {
    const ctrl = new AbortController();
    fetch(url, { signal: ctrl.signal })
      .then(r => r.json()).then(setData)
      .catch(e => { if (e.name !== 'AbortError') setError(e.message); })
      .finally(() => setLoad(false));
    return () => ctrl.abort();
  }, [url]);
  return { data, loading, error };
}

Prerequisites

  • React >= 17

Pro Tips

  • → Use SWR or React Query for caching and revalidation.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
3 min
Published
Oct 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.