Data fetching is a common task in React applications. To avoid duplicating logic for handling loading and error states across multiple components, you can create a custom hook. The useFetch hook encapsulates the useEffect logic for fetching data from a given URL. It returns the data, a loading state, and any potential error, which you can then use in your components to render the UI accordingly. This pattern promotes code reuse and separation of concerns.
React: Basic Fetch Hook
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [url]);
return { data, loading, error };
}
Clean and simple, love it.