React: Data Fetching (Step 3)
1. Fetching Data in React
To fetch external API data in a React component, developers primarily use the fetch API or the axios library. This logic is typically executed inside a useEffect hook.
2. Basic Fetching with useEffect
Here is an example of fetching data only once when the component mounts.
import { useState, useEffect } from 'react';
function UserProfile() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(res => res.json())
.then(data => {
setUser(data);
setLoading(false);
});
}, []); // Empty array: Executes once on mount
}
3. Handling Loading and Error States
For a better User Experience (UX), it's essential to inform the user that data is loading and to handle potential exceptions like network errors.
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url);
if (!res.ok) throw new Error('Failed to fetch data.');
const result = await res.json();
setData(result);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
4. Modern Alternative: TanStack Query (React Query)
In professional environments, libraries like React Query are widely used because they provide built-in features for caching, automatic re-requests, and state management.
// React Query example (Conceptual)
const { data, isLoading } = useQuery(['user'], fetchUser);