React fetch hook
Open this example in our interactive code editor to experiment with it.
Try the EditorFetch 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
urland optionaloptionsobject, managing three pieces of state:data,loading, anderror. - The hook uses useEffect to trigger the fetch when the component mounts or the
urlchanges, with an async function inside to handle the promise-based fetch API. - try/catch/finally ensures errors are caught and
loadingis always set tofalsewhen 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
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.
Related Pills
React Dark Mode hook
We'll create useDarkMode hook to switch between light and dark themes.
Event handlers arguments in React
onClick, onChange, onBlur... We usually pass a reference to the function handler but how do we add more arguments instead of just the event itself?
React counter hook
Let's create a custom hook for tracking the counter state and exposing the current counter value with increment, decrement handlers.