Custom Hook for Data Fetching in React
Table of contents
Implementation
This hook will manage the fetching of data from an API, including handling the loading state and any errors.
import { useState, useEffect } from 'react';
function useFetchData(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('Network response was not ok');
}
const json = await response.json();
setData(json);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
}
Usage in Components
To use this hook in your React components, you would import them and call them within the components, providing the necessary arguments (like the URL for useFetchData
). These hooks abstract away the complex logic of data fetching and form handling, making your components cleaner and more focused on the presentation logic.
import { useFetchData } from './useFetchData';
function MyComponent() {
const { data, loading, error } = useFetchData('https://api.example.com/data');
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>An error occurred: {error.message}</div>;
}
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
Real-World Example
A blog platform might use this hook to fetch and display articles from an API. The useFetchData
hook simplifies the process of requesting and displaying data, handling loading states, and displaying errors if the fetch fails.