š Reusable API Calls in React ā The Hook Pattern That Scales
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:
useEffectto manage lifecycleAbortControllerto 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.