TypeScript

useFetch — Minimal Data Fetching Hook

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A tiny self-contained data-fetching hook with loading/error/data states and AbortController cleanup on unmount. Good baseline before reaching for TanStack Query.
TypeScript
Raw
import { useEffect, useState } from 'react';

type State<T> =
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error';   error: Error };

export function useFetch<T>(url: string): State<T> {
  const [state, setState] = useState<State<T>>({ status: 'loading' });

  useEffect(() => {
    const ctl = new AbortController();
    setState({ status: 'loading' });
    fetch(url, { signal: ctl.signal })
      .then(async r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json() as Promise<T>;
      })
      .then(data => setState({ status: 'success', data }))
      .catch(error => { if (error.name !== 'AbortError') setState({ status: 'error', error }); });
    return () => ctl.abort();
  }, [url]);

  return state;
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.