JAVASCRIPT
Custom useFetch Hook for API Data
Create a reusable custom useFetch hook in React to elegantly handle data fetching from APIs, managing loading, error, and success states for cleaner components.
import { useState, useEffect } from 'react';
const 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, JSON.stringify(options)]); // Dependency array: re-fetch if URL or options change
return { data, loading, error };
};
// Example Usage (in a component)
/*
function UsersList() {
const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/users');
if (loading) return <p>Loading users...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<div>
<h1>Users</h1>
<ul>
{data && data.map(user => (
<li key={user.id}>{user.name} ({user.email})</li>
))}
</ul>
</div>
);
}
// To use, render <UsersList /> in your App component.
*/
How it works: This snippet provides a `useFetch` custom hook for encapsulating common data fetching logic. It manages `loading`, `error`, and `data` states, abstracting away the boilerplate of `useEffect` and `useState` for API calls. The hook automatically refetches data when the `url` or `options` dependencies change, providing a clean and reusable way to integrate external data into React components.