How to fetch data in React with fetch API
Fetching data in React with the native fetch API enables HTTP requests for dynamic content loading without external dependencies. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented data fetching in thousands of React applications for dashboards, user profiles, and real-time data displays. From my expertise, the most effective approach is using useEffect hook with fetch API for clean data loading and error handling. This method provides built-in browser support with proper loading states and error management for robust applications.
Use useEffect
hook with fetch
API to load data when component mounts.
import { useState, useEffect } from 'react'
function UserProfile({ userId }) {
const [user, setUser] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
const fetchUser = async () => {
try {
setLoading(true)
const response = await fetch(`/api/users/${userId}`)
if (!response.ok) {
throw new Error('Failed to fetch user')
}
const userData = await response.json()
setUser(userData)
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
}
fetchUser()
}, [userId])
if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error}</div>
if (!user) return <div>No user found</div>
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
)
}
The useEffect hook triggers the fetch request when the component mounts or when dependencies change. Use async/await for clean promise handling and check response.ok for HTTP error detection. Manage loading, error, and success states separately for comprehensive user feedback.
Best Practice Note:
This is the same fetch pattern we use in CoreUI React components for reliable data loading. Always handle response.ok checks and provide loading states to create smooth user experiences during API calls.