🔁 Reusable API Calls in React — The Hook Pattern That Scales
0 Comments

When working with React, it’s easy to fall into the trap of writing the same fetch + useEffect logic over and over. That’s fine for small projects—but when your app grows, things quickly get messy:
- Redundant loading/error handling
- Memory leaks from unmounted components
- Hard-to-test async logic
- Poor reusability across components
🔧 Here’s a better way:
I implemented a reusable custom hook using:
useEffect
to manage lifecycleAbortController
to cancel requests if the component unmounts- TypeScript for fully typed API responses
- A hook pattern (useApi) to centralize logic
⸻
What You Get:
✅ One place to manage API behavior
✅ Built-in cleanup logic for safety
✅ Easily extendable for pagination, revalidation, retries
✅ Cleaner, testable, and DRY code
const { data, loading, error } = useApi((signal) => fetch('/api/products', { signal }).then((res) => res.json()) );
Want to ship cleaner frontend code? This is one of those patterns that scales beautifully with your app.
⸻
👉 Want more patterns like this? Follow me @kheang for practical, real-world frontend engineering tips.