Data fetching in useEffect
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
useEffect(() => {
fetch(`/api/u/${id}`).then(setUser);
}, [id]);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.
- X post by aidenybai
- skill: react-doctor
- owner's notes
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"
}
}
}
useEffect. That races on fast re-renders and refetches on every mount.