useFetch Hook
A custom React Hook for handling API requests with loading/error states and TypeScript support
Code
import { useState, useEffect, useCallback } from 'react';
type FetchState<T> = {
data: T | null;
loading: boolean;
error: Error | null;
};
function useFetch<T>(url: string, options?: RequestInit): FetchState<T> & { refetch: () => void } {
const [state, setState] = useState<FetchState<T>>({
data: null,
loading: true,
error: null
});
const fetchData = useCallback(__TOKEN_11__ () => {
setState(prev => ({ ...prev, loading: true }));
try {
const response = await fetch(url, options);
__TOKEN_15__ (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json() as T;
setState({ data, loading: false, error: null });
} __TOKEN_20__ (error) {
setState({ data: null, loading: false, error: error as Error });
}
}, [url, options]);
useEffect(() => {
fetchData();
}, [fetchData]);
return { ...state, refetch: fetchData };
}
// Usage example
// type User = { id: number; name: string };
// const { data: users, loading, error, refetch } = useFetch<User[]>('/api/users');