react Advanced

React fetch hook

React fetch hook
React Fetch Hook

Open this example in our interactive code editor to experiment with it.

Try the Editor

Fetch them all!

import { useState, useEffect } from "react";

const useFetch = (url, options) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const response = await fetch(url, options);
        const json = await response.json();
        setData(json);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, loading, error };
};

export default useFetch;
import useFetch from "./useFetch";

export default function App() {
  const { data, loading, error } = useFetch(
    "https://jsonplaceholder.typicode.com/posts/1"
  );

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.body}</p>
    </div>
  );
}

Summary

  • useFetch accepts a url and optional options object, managing three pieces of state: data, loading, and error.
  • The hook uses useEffect to trigger the fetch when the component mounts or the url changes, with an async function inside to handle the promise-based fetch API.
  • try/catch/finally ensures errors are caught and loading is always set to false when the request completes, regardless of success or failure.
  • The hook returns { data, loading, error }, giving components everything they need to render loading states, error messages, and fetched content.
  • This pattern is a simplified version of what libraries like SWR or React Query provide, but it is a great exercise to understand how data fetching works under the hood.

Try this in our interactive code editor

Practice hands-on with our built-in code sandbox.

Open Code Editor
Adrian Bigaj
Adrian Bigaj

Creator of BigDevSoon

Full-stack developer and educator passionate about helping developers build real-world skills through hands-on projects. Creator of BigDevSoon, a vibe coding platform with 21 projects, 100 coding challenges, 40+ practice problems, and Merlin AI.