Find the step-by-step explanation of the useFetch custom hook in React that helps in fetching the data from an API and handling loading, error states.
Anuj Sharma
Last Updated Oct 25, 2025
Learn how to create a custom hook in React, useFetch, that simplifies data fetching from APIs and manages loading and error states efficiently.
import React, { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
The hook begins by setting up three pieces of state:
data → stores the fetched API result
loading → tracks if the request is still ongoing
error → captures any failure during the fetch
These states help manage the complete request lifecycle.
A useEffect runs automatically whenever the url changes.
This ensures that new data is fetched each time a different endpoint is passed.
Inside the effect, an asynchronous function performs the API request using the Fetch API.
This allows React to handle network requests cleanly without blocking the UI.
If the request succeeds, the fetched data is parsed and stored in data.
If it fails (due to network or response issues), the error is caught and stored in error.
Once the request completes — whether successful or not — the loading flag is set to false, so the component knows the operation is done.
Finally, the hook returns { data, loading, error }, giving the component everything it needs to render UI accordingly (loading spinner, data display, or error message).
Now, let's see how we can use the useFetch custom hook in a React component.
const MyComponent = () => {
const { data, loading, error } = useFetch('https://api.example.com/data');
if (loading) return <div>Loading...</div>;
if (error) return Error: {error.message};
return (
<div>
<h2>Fetched Data</h2>
<p>{JSON.stringify(data)}</p>
</div>
);
};
Let's consider a real-world scenario where you need to fetch data from an API using the useFetch custom hook.
import React from 'react';
import { useFetch } from './useFetch';
export function App(props) {
const { data, loading, error } = useFetch('https://dummyjson.com/test');
if (loading) return <div>Loading...</div>;
if (error) return <>Error: {error.message}</>;
return (
<div>
<h2>Fetched Data</h2>
<p>{JSON.stringify(data)}</p>
</div>
);
}
Custom hooks like useFetch in React provide a powerful way to encapsulate and reuse complex logic across components. By centralizing data fetching and state management, custom hooks promote code reusability and maintainability in frontend applications.
Start leveraging custom hooks in your React projects to streamline your development process and enhance code quality.
Advertisement
Advertisement
Anuj Sharma
Last Updated Oct 2, 2025
Explore Polyfill for map, filter and reduce array methods in JavaScript. A detailed explanation of Map, filter and reduce polyfills in JS helps you to know the internal working of these array methods.
Alok Kumar Giri
Last Updated Jun 2, 2025
Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.
Vijay Sai Krishna vsuri
Last Updated Aug 21, 2025
A Quick guide about popstate event in JavaScript, If you’ve ever hit the back button in your browser and wondered how your Single-Page Application knows which view to render, this guide is for you.
Anuj Sharma
Last Updated Oct 26, 2025
In this post, we will going to cover the step-by-step implementation of Infinite Currying Sum with a code example. This is one of the most common JavaScript Interview questions.
Anuj Sharma
Last Updated Aug 3, 2025
Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.
Anuj Sharma
Last Updated Oct 26, 2025
Understand the step-by-step implementation of Infinite Currying Multiplication in JavaScript with a code example.
Subscribe to FrontendGeek Hub for the frontend interview preparation, interview experiences, curated resources and roadmaps.
© 2024 FrontendGeek. All rights reserved