JAVASCRIPT
Robust Data Fetching with Cancellation using React's `useFetch` Hook
Create a versatile `useFetch` React hook for handling asynchronous data fetching, including loading and error states, and crucial request cancellation on component unmount.
import { useState, useEffect } from 'react';
function useFetch(url, options) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortController = new AbortController();
const signal = abortController.signal;
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch(url, { ...options, signal });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json = await response.json();
setData(json);
setError(null);
} catch (err) {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
} else {
setError(err);
}
} finally {
setLoading(false);
}
};
fetchData();
// Cleanup function to abort fetch request on unmount
return () => {
abortController.abort();
};
}, [url, JSON.stringify(options)]); // Re-run if URL or options change
return { data, loading, error };
}
export default useFetch;
// Example Usage:
// function UserProfile({ userId }) {
// const { data: user, loading, error } = useFetch(`https://api.example.com/users/${userId}`);
//
// if (loading) return <div>Loading user...</div>;
// if (error) return <div>Error: {error.message}</div>;
// if (!user) return null;
//
// return (
// <div>
// <h2>{user.name}</h2>
// <p>Email: {user.email}</p>
// </div>
// );
// }
How it works: The `useFetch` hook provides a standardized way to manage asynchronous data fetching in React components. It tracks loading, error, and data states, returning them for easy consumption. Crucially, it integrates `AbortController` to cancel ongoing fetch requests when the component unmounts or its dependencies (like `url` or `options`) change, preventing memory leaks, undesirable state updates on unmounted components, and improving request efficiency.