Custom Hook Method
π― Why Create a Custom Hook?β
While using useEffect with fetch() works, it has some drawbacks:
Code Duplication β If multiple components need to fetch data, youβll have to repeat the same logic.
Hard to Manage β Fetching logic is tied directly to the component, making it less reusable.
No Reusability β Cannot be easily shared across multiple components.
Solution? β A Custom Hook!
β¨ Benefits of Using a Custom Hookβ
β
Reusable β Define once, use anywhere in your app.
β
Cleaner Code β Keeps component logic focused on UI.
β
Encapsulated Logic β Fetching, error handling, and state management are handled in one place.
β
Easier Testing & Maintenance β Modify fetching logic in one file instead of multiple components.
π§ Creating a Custom Hook for Data Fetchingβ
import { useState, useEffect } from "react";
function 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 (error) {
setError(error.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]); // Re-fetch if URL changes
return { data, loading, error };
}
π Using the Custom Hook in a Componentβ
Now that we have useFetch, we can use it in any component!
import React from "react";
import useFetch from "./useFetch"; // Import the custom hook
export default function DataComponent() {
const { data, loading, error } = useFetch("https://api.example.com/data");
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
π§ Whatβs Happening Inside?β
-
Custom Hook (
useFetch)- Initializes
data,loading, anderrorstates. - Uses
useEffectto fetch data whenever theurlchanges. - Returns the state variables (
data,loading,error).
- Initializes
-
Component (
DataComponent)- Calls
useFetchwith a URL. - Uses returned values (
data,loading,error) to display the UI.
- Calls
Pros & Cons of Using a Custom Hookβ
Advantagesβ
βοΈ Reusable β Can be used in multiple components without duplicating logic.
βοΈ Cleaner Code β Separates data-fetching logic from UI components.
βοΈ Scalable β Easily extendable (e.g., add caching, retries, etc.).
Disadvantagesβ
β Still Fetches on Every Mount β No built-in caching (can use SWR or React Query to fix this).
β No Global State Management β Each component using useFetch fetches its own data separately.
β οΈ When Should You Avoid a Custom Hook?β
π« If you need automatic caching, consider using SWR or React Query instead.
π« If multiple components share the same data globally, use React Context or Zustand.
π« If you need real-time updates, consider WebSockets or polling.
For larger applications, you may want to integrate React Query, Zustand, or Redux for state management and caching! π