Skip to content

Instantly share code, notes, and snippets.

@RichLewis007
Last active September 9, 2025 09:15
Show Gist options
  • Save RichLewis007/94dc04cd0150766bff8cd23c984843c0 to your computer and use it in GitHub Desktop.
Save RichLewis007/94dc04cd0150766bff8cd23c984843c0 to your computer and use it in GitHub Desktop.
Custom React Hook for fetching data using TypeScript.

Custom React Hook for fetching data - useFetch

TypeScript React

Custom React hook for fetching data using TypeScript.

Tags

react, typescript, hooks, mit-license

Code

import { useState, useEffect } from "react";

function useFetch<T>(url: string): { data: T | null, loading: boolean, error: Error | null } {
  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 res = await fetch(url);
        if (!res.ok) throw new Error(`Error: ${res.status}`);
        const json = await res.json();
        setData(json);
      } catch (err: any) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [url]);

  return { data, loading, error };
}

export default useFetch;

MIT (c) Rich Lewis


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment