I want to call fetch just once when component loads and prevent subsequent fetches in React.StrictMode.
Is anything wrong with it?
let ignore = false;
useEffect(() => {
if (ignore) return;
fetchStuff().then(res => {
setResult(res)
})
return () => { ignore = true }
}, [])
2
Answers
If you refer
strict mode
to<React.StrictMode>
, your code does not prevent from calling twice. Because thereturn
part runs when a component unmounts.The code you’ve shared will only avoid setting state in an unmounted component, or ignore the first result in case of the double mounting caused by
StrictMode
, but it cannot prevent making 2 HTTP calls.If you want to prevent multiple calls, you have to use a library like TanStack Query, SWR or RTK Query.