JAVASCRIPT
React useFetch Hook for Asynchronous Data Fetching
Simplify asynchronous data fetching in React with a custom `useFetch` hook, providing clear loading, error, and data states for robust UI development.
import { useState, useEffect, useCallback } from 'react';
function useFetch(url, options) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fetchData = useCallback(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);
}
}, [url, options]);
useEffect(() => {
fetchData();
}, [fetchData]);
return { data, loading, error };
}
// Example Usage:
/*
function UserProfile({ userId }) {
const { data, loading, error } = useFetch(`https://api.example.com/users/${userId}`);
if (loading) return <div>Loading user data...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!data) return null;
return (
<div>
<h1>{data.name}</h1>
<p>Email: {data.email}</p>
</div>
);
}
*/
How it works: The `useFetch` hook provides a standardized way to handle asynchronous data fetching in React components. It manages the `loading`, `error`, and `data` states, abstracting away the boilerplate of `try-catch` blocks and state updates. The `fetchData` function is memoized with `useCallback` to prevent unnecessary re-creations, and `useEffect` ensures the data is fetched when the component mounts or the URL/options change, providing a clean interface for consuming API data.