Problem Overview
Creating a custom hook in React for data fetching can streamline your components and improve code reusability. Follow these steps to build a simple data-fetching hook:
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Network response was not ok');
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, error, loading };
};
export default useFetch;This hook takes a URL as an argument and returns the fetched data, any errors that occur, and a loading state. You can use this hook in your components like this:
const { data, error, loading } = useFetch('https://api.example.com/data');This approach keeps your components cleaner and focused on rendering, while the data-fetching logic is encapsulated in the custom hook.