redline
MediumReacteffect-fetch

Data fetching in useEffect

Data fetching in useEffect. Fetches data inside useEffect. That races on fast re-renders and refetches on every mount.

This is how the comment reads inline, under the flagged line.

Why it matters

Fetching in an effect races when props change quickly, double-fetches in Strict Mode and has no cache.

What to do

Use the framework's data loading (server components, loaders) or a query library.

Examples

Flagged
useEffect(() => {
  fetch(`/api/u/${id}`).then(setUser);
}, [id]);
Better
const { data: user } = useQuery(['user', id], () => getUser(id));

What it catches

It reads the shape of the code: functions, blocks, loops and calls. Languages: TypeScript and JavaScript. Scope: All files. These cases are the rule's own tests: the first set must be flagged and the second must not.

Flagged

useEffect(() => {
  fetch(url).then(setUser);
}, [url]);

Left alone

useEffect(() => {
  track(page);
}, [page]);

Research

Effects with no dependency array, data fetching in effects, and effects that copy derived values into state. They cause extra renders, loops, races and double fetches.

Turn it off or change it

In a config file for the CLI, or in the API's rules field:

{
  "rules": {
    "disable": [
      "effect-fetch"
    ],
    "severity": {
      "effect-fetch": "low"
    }
  }
}

Read the source or report a false positive.