Article with Code Snippets

Building a Custom React Hook for API Calls

A step-by-step guide to creating a reusable hook for handling data fetching with loading and error states.

DCDavid ChenSenior Developer
November 10, 2025
8 min read
React hooks illustration

Custom hooks are one of React's most powerful features. They let you extract component logic into reusable functions. In this article, we'll build a hook for API calls that handles loading, errors, and data.

The Basic Structure

Let's start with a basic hook that manages our three states: data, loading, and error. We'll use TypeScript generics to make it type-safe.

useApi.ts

Adding Refetch Capability

Often you'll want to refetch data after a user action. Let's add a refetch function to our hook.

useApi.ts

Usage Example

Here's how you'd use the hook in a component. The generic type ensures type safety throughout.

UserProfile.tsx

Key Takeaways

  • Custom hooks encapsulate reusable logic
  • TypeScript generics provide type safety
  • useCallback prevents unnecessary re-fetches
  • Exposing a refetch function adds flexibility

This is just the foundation. You could extend it with caching, request cancellation, or optimistic updates. The beauty of custom hooks is that complexity stays encapsulated.

About this block

Article with Code SnippetsPRO

Technical article with code blocks featuring language labels, filenames, and copy-to-clipboard buttons. Ideal for programming tutorials.

More Post blocks

View all Post
PRO

post32

Highlightable Content

Article with text selection and highlighting feature allowing readers to save key quotes. Great for reference material or learning content.

PRO

post4

Clean Article Format

Minimal design with tags above title and author metadata below. Perfect for technical articles or educational content that prioritizes readability.

PRO

post55

Interactive Checklist Article

Article with checkable items, progress tracking, and print/download options. Perfect for actionable guides and checklists.

PRO

post12

Article with Related Posts

Two-column layout with main article and right sidebar containing related article cards with thumbnails. Perfect for discovery-focused content.

PRO

post57

Article with Comments

Article with full comment system, replies, likes, and featured comments. Perfect for community-driven discussions.

PRO

post27

News Article Sidebar

Newspaper-style layout with byline, serif typography, author bio sidebar, and trending articles list. Ideal for news or journalism.