Every React tutorial starts with this:
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData);
}, []);
It works, until one of these problems shows up.
The problems
Race conditions come first. If the dependency changes fast (search input, tab switches), multiple requests fire, and the last response might not be from the last request.
// Bug: typing "react" fires 5 requests
// Response for "r" might arrive after "react"
useEffect(() => {
fetch(`/api/search?q=${query}`)
.then(res => res.json())
.then(setResults);
}, [query]);
There is also no cleanup. You need an AbortController to cancel a request, and most devs forget.
Then come the loading and error states. You end up with 3-4 state variables (data, loading, error, isRefetching) that are easy to get wrong.
And you get waterfalls: the parent fetches, then renders its children, then the children fetch. Those requests run one after another when they could run together.
What I use instead
I use Server Components in the Next.js App Router. The data is fetched on the server, so the component renders with it already there and needs no loading state. There are no race conditions either.
// Just works. No useEffect, no loading state.
export default async function Dashboard() {
const data = await fetchDashboardData();
return <DashboardView data={data} />;
}
For cases that have to run in the browser (real-time updates, optimistic mutations), I use React Query or SWR. They handle caching, duplicate requests and race conditions.
function SearchResults({ query }) {
const { data, isLoading } = useQuery({
queryKey: ['search', query],
queryFn: () => fetchSearch(query),
});
if (isLoading) return <Skeleton />;
return <ResultList items={data} />;
}
When useEffect is still fine
- Subscriptions (WebSocket, event listeners)
- DOM manipulation (focus, scroll position)
- Syncing external stores
I almost never use it for data fetching anymore.