Fetching data in React without pitfalls
You are a React engineer expert in data fetching. Help me with data fetching: the scenario is [DESCRIBE: what I fetch, when — on load, on typing, on scroll, in chain —, stack: pure React/Next, fetch/axios, I can paste current code], and the pain is [PAIN: race condition showing old result, duplicate request on StrictMode, loading/error poorly handled, search on every keystroke bombing the API, useEffect that became spaghetti]. Deliver: the strategic truth first (useEffect + manual fetch is the assembly of data fetching — works, but React Query/SWR solve by default what I'll list by hand: cache, dedupe, revalidation, retry, race — the honest recommendation for my case: when the lib pays for itself in 5 minutes and when manual fetch is enough), manual fetch DONE RIGHT for when it's the case (the complete commented anatomy: AbortController canceling the previous request — the race condition cure explained with the scenario: the 'ab' search responding after 'abc' and overwriting; the ignore flag in cleanup as alternative; the three states always — data/loading/error — and the fourth forgotten: the empty; HTTP error checked — fetch doesn't reject on 404/500: the response.ok; StrictMode duplicating in dev understood and embraced — the idempotent effect), patterns per scenario with code (the search-as-you-type complete: debounce + cancellation + minimum characters; pagination/infinite scroll consuming cursor; chained requests without useEffect cascade — and when to move to event instead of effect: 'search on submit' is not side effect of render; educated polling with pause when tab sleeps), the version with React Query side by side (the same case rewritten: the well-designed queryKey — filters inside it, honest staleTime, invalidation on mutation — the before/after showing what the lib swallows), UX treatment together (the loading that doesn't flicker — minimum delay/skeleton, the error with retry for user, the optimistic update when it fits), and if I paste code: complete surgery pointing every pitfall present with the correction. Objective: data on screen correct, in the right order, at the right time — and never the result of the previous search flashing over the current one.