Conceptual Question

What are common data fetching pitfalls in React?

React Ecosystem

What are common data fetching pitfalls in React?

A profile page loads Ava, then you quickly switch to Noor. Noor appears first. A moment later Ava’s photo replaces Noor’s, even though the URL still points to Noor. How would you fix this and keep the loading and error states correct?

Interview answer

Give every request a data identity, such as the user ID and any filters that change the result. Cancel obsolete work when possible and prevent an obsolete request from writing to the current screen. Check the HTTP response status and represent loading, results, empty data, and errors explicitly. Move shared fetching to a route loader or query cache when you need deduplication, parallel loading, or reuse across screens.

Protect the screen from obsolete results

This hook manages one client-side request. Each effect run has its own signal. A result is applied only while that run is active, including after the body has been parsed. The current ID check also prevents a flash of the previous user during the render before the new effect starts.

JSX
import { useEffect, useState } from 'react';
function useProfile(userId) {
const [result, setResult] = useState(null);
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
setResult({ userId, status: 'loading' });
async function load() {
try {
const response = await fetch('/api/users/' + encodeURIComponent(userId), { signal });
if (!response.ok) throw new Error('Profile request failed: ' + response.status);
const profile = await response.json();
if (!signal.aborted) {
setResult({ userId, status: 'success', profile });
}
} catch (error) {
if (!signal.aborted) setResult({ userId, status: 'error', error });
}
}
void load();
return () => controller.abort();
}, [userId]);
return result?.userId === userId ? result : { userId, status: 'loading' };
}

fetch() can fulfill with a 404 or 500, so check response.ok before treating the body as a success. An empty successful result can have its own message. A network error should offer recovery. An obsolete request can be dropped silently. In development, React Strict Mode can run an extra setup and cleanup cycle, which exposes effects that fail to clean up.

Choose the right place to load

SituationPractical choice
A route needs data before it can renderUse a framework’s server or route data API where available
Tabs or components share the same client dataUse a query cache and include resource ID, filters, and other result-defining values in the key. Clear or scope user-specific data across account switches.
Two panels only need the current user IDStart the requests together. Handle failures independently if each panel can still render on its own.
One API needs an ID returned by the otherKeep the dependency explicit. Consider a combined endpoint if that chain consistently blocks the screen.

Interview follow-up

How do you test the race? Hold the request for Ava, load Noor, and release Noor’s response first. Release Ava’s response last and assert that Noor remains visible. Add a test for a 404 and another for an empty successful result. Each outcome should have a distinct UI state.

Further reading · React guidance on fetching with effects · React Strict Mode

Continue with nearby questions from the same topic cluster.