Back to Blog
ReactPublished

Use useFetch Hook

Last updated: 4/5/2025

🎙️ "Hey everyone! 🚀 Today, let's break down this custom React hook called useFetch in under a minute!

What does it do?

This hook helps you fetch data from an API and manage loading, error, and response states easily. It's perfect for reusing in multiple components!

📜 Here's how it works:

1️⃣ State Management:

We use useState to track three things:

  • data for storing the API response,
  • loading for the loading state, and
  • error for any issues during the fetch.

2️⃣ Effect Hook:

We use useEffect to perform the fetch whenever the url changes. Inside, we define an async function called fetchData.

3️⃣ Fetching Logic:

  • Start by setting loading to true.
  • Use the fetch API to get data from the URL and parse it with .json().
  • If successful, store the result in data.
  • If there's an error, we catch it and set the error state.
  • Finally, set loading to false.

4️⃣ Return Values:

This hook returns an object with { data, loading, error }, so you can use it directly in your components.

Why use it?

It simplifies your API calls and keeps your components clean. Just call useFetch(url) and you’re good to go!

That's it! Simple, reusable, and efficient. Give it a try and level up your React projects today. 🔥

Don’t forget to hit like and subscribe for more coding tips! See you in the next one. 👋"