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.
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.
Similar Modules
Copy to Clipboard Button
React component that copies text to clipboard and shows a Copied! confirmation.
typescript
·
Beginner
Framer Motion Fade-In Wrapper
Reusable component that fades any child element in on mount.
typescript
·
Beginner
Compound Component Pattern
Implement a flexible Tabs component using React Context and compound component pattern.
typescript
·
Intermediate