JAVASCRIPT
Custom Hook for Fetching Data with Loading and Error States
Implement a reusable React custom hook for handling asynchronous data fetching, including built-in loading and error state management, simplifying API calls in components.
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 fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url, options]);
return { data, loading, error };
}
How it works: The `useFetch` custom hook simplifies data fetching from an API endpoint. It manages `data`, `loading`, and `error` states internally, providing a clean interface for components to consume. Upon mounting or when the `url` or `options` change, it initiates an asynchronous fetch request, updating its internal states based on the response, network errors, or parsing issues.