Implement useFetch() Custom Hook in React (Interview)
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 Feb 21, 2026

Implement useFetch() Custom Hook in React
Learn how to create a custom hook in React, useFetch, that simplifies data fetching from APIs and manages loading and error states efficiently.
Step 1: Define the useFetch Hook
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 };
};
1. Initialize States
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.
2. Trigger Fetch on URL Change
A useEffect runs automatically whenever the url changes.
This ensures that new data is fetched each time a different endpoint is passed.
3. Fetch Data Asynchronously
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.
4. Handle Success and Errors
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.
5. Update Loading Status
Once the request completes — whether successful or not — the loading flag is set to false, so the component knows the operation is done.
6. Return Results to the Component
Finally, the hook returns { data, loading, error }, giving the component everything it needs to render UI accordingly (loading spinner, data display, or error message).
Step 2: Using the useFetch Hook
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>
);
};
Real-World Example: Fetching Data from an API
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>
);
}
Final Thoughts
Custom hooks like useFetch in React provide a powerful way to encapsulate and reuse complex logic across components. By moving data fetching and state management into common place, custom hooks promote code reusability and maintainability in frontend applications.
Start leveraging custom hooks in your React projects to enhance code quality and this will also help to write clean code.
Happy Coding :)
Learn Next
A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me 🚀
Learn Next
Featured
100+ Top React JS Interview Questions And Answers
Comments
Be the first to share your thoughts!
No comments yet.
Start the conversation!
Share your expertise
Publish a blog or quick notes on topics you know well — your write-up could be the answer someone needs before their next frontend interview.
Build your portfolio
Help the community
Sharpen your skills
Earn goodies
Other Related Blogs
20 Most Asked Custom Hooks In React for Interviews
Anuj Sharma
Last Updated Jun 27, 2026
Explore the Most Common Custom Hooks in React asked in the React Interviews. It includes the code example of all the custom hooks in react for a quick revision before interview.
How to create custom useInfiniteScroll Hook in React
Anuj Sharma
Last Updated Jun 20, 2026
Learn how to implement useInfiniteScroll hook in react to handle long list of items efficiently using intersection observer internally.
Implement Custom useKeyPress Hook in React
Anuj Sharma
Last Updated Jun 11, 2026
Explore the code implementation of the custom useKeyPress Hook to monitor the key press events in React that can help to integrate actions based on the key press.
Implement Custom useMediaQuery Hook in React
Anuj Sharma
Last Updated Jun 11, 2026
Explore code implementation of the custom useMediaQuery hook to handle the website responsiveness for different devices using common custom hook code
Implement custom useScrollPosition Hook in React
Anuj Sharma
Last Updated Jun 11, 2026
Explore the code implementation of the custom useScrollPosition hook to monitor the scroll position to invoke actions based on the scrolling in reactjs.
Implement custom useClipboard() Hook in React
Anuj Sharma
Last Updated Jun 11, 2026
Code implementation of custom useClipboard hook to manage copy the values to the clipboard with detailed explanation.
React useCopyToClipboard Hook: Explanation & Usage
Anuj Sharma
Last Updated Jun 11, 2026
Explained the step-by-step implementation and usage of custom useCopyToClipboard Hook to manage the interaction with the clipboard in react app.
Implement Custom useIntersectionObserver Hook in React
Anuj Sharma
Last Updated Jun 11, 2026
Explore the code implementation of a custom useIntersectionObserver hook in React, which helps to manage the infinite scroll in a React application.
