šŸ” 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 lifecycle
  • AbortController 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.