Building a Custom React Hook for API Calls
Learn how to create a custom React hook for handling API requests with TypeScript support
By Ajith joseph · · Updated · 5 min read · beginner
A practical guide to creating a reusable hook for handling API requests in React applications.
Understanding Custom Hooks
Custom hooks are a powerful feature in React that allows you to extract component logic into reusable functions.
When to Use Custom Hooks
- Reusing stateful logic between components
- Abstracting complex logic
- Maintaining clean component code
The Custom Hook Implementation
Here's how we can implement our API hook:
function useApi<T>(url: string) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setData(json);
} catch (err) {
setError(err instanceof Error ? err : new Error('Unknown error'));
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
Error Handling
Proper error handling is crucial for a robust API hook.
Common Error Scenarios
- Network failures
- Invalid JSON responses
- Server errors
Usage Examples
Here's how to use the hook in your components:
function UserProfile({ userId }: { userId: string }) {
const { data, loading, error } = useApi<User>(`/api/users/${userId}`);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!data) return null;
return <div>{data.name}</div>;
}