JAVASCRIPT
Asynchronous Data Fetching in React with `useEffect`
Learn to fetch data from an API in React components using the `useEffect` hook, managing loading states and error handling for robust applications.
import React, { useState, useEffect } from 'react';
function useFetchData(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
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]); // Re-run effect if URL changes
return { data, loading, error };
}
// Example Usage:
// function MyComponent() {
// const { data, loading, error } = useFetchData('https://api.example.com/items');
// if (loading) return <div>Loading items...</div>;
// if (error) return <div>Error: {error.message}</div>;
// if (!data) return null;
// return (
// <div>
// <h1>Items</h1>
// <ul>
// {data.map(item => (
// <li key={item.id}>{item.name}</li>
// ))}
// </ul>
// </div>
// );
// }
How it works: This custom hook `useFetchData` demonstrates a common pattern for fetching asynchronous data in React. It utilizes `useState` to manage the data, loading state, and any errors. The `useEffect` hook performs the data fetching when the component mounts or when the `url` dependency changes. It includes proper error handling and sets loading states, making API calls robust and user-friendly.