Back to Snippets
useFetch Hook
typescript
React
A custom hook for data fetching with loading and error states.
Code
1import { useState, useEffect } from "react";
2
3interface FetchState<T> {
4data: T | null;
5loading: boolean;
6error: Error | null;
7}
8
9function useFetch<T>(url: string): FetchState<T> {
10const [state, setState] = useState<FetchState<T>>({
11data: null,
12loading: true,
13error: null,
14});
15
16useEffect(() => {
17const controller = new AbortController();
18
19const fetchData = async () => {
20try {
21setState(prev => ({ ...prev, loading: true }));
22const response = await fetch(url, {
23signal: controller.signal
24});
25
26if (!response.ok) {
27throw new Error(`HTTP error! status: ${response.status}`);
28}
29
30const data = await response.json();
31setState({ data, loading: false, error: null });
32} catch (error) {
33if (error instanceof Error && error.name !== "AbortError") {
34setState({ data: null, loading: false, error });
35}
36}
37};
38
39fetchData();
40
41return () => controller.abort();
42}, [url]);
43
44return state;
45}
46
47// Usage
48const { data, loading, error } = useFetch<User[]>("/api/users");Details
Language
typescript
Category
React