Creating Custom Hooks for Data Fetching in Sub Components
Illustrates the creation and usage of a custom hook within a sub component for fetching additional data from an API, allowing for dynamic and asynchronous data updates.
import { useState, useEffect } from 'react';
import axios from 'axios';
// Custom hook for fetching data
export const useFetchData = (url) => {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(url);
setData(response.data);
setError(null);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
fetchData();
}, [url]);
return { data, isLoading, error };
};
Defines a custom hook useFetchData that takes a URL as its argument. It uses axios for making HTTP requests. This hook fetches data from the provided URL, manages the loading state, and handles any errors that may occur during the fetch operation. The fetched data, loading state, and any error information are returned by the hook.
import React from 'react';
import { useFetchData } from './useFetchData';
// Component using the custom hook
const DataDisplayComponent = ({ url }) => {
const { data, isLoading, error } = useFetchData(url);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error fetching data</p>;
return (
<div>
<h2>Data Fetched</h2>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default DataDisplayComponent;
Demonstrates how to use the custom hook useFetchData within a functional component, DataDisplayComponent. The component accepts a URL as a prop, uses the custom hook to fetch data from that URL, and then renders the data or displays a loading message or an error message based on the current state of the data fetch.