With React 16.8.6 (it was good on previous version 16.8.3), I get this error when I attempt to prevent an infinite loop on a fetch request
./src/components/Bu
I only want to run [
fetchBusinesses
] once in the beginning similar tocomponentDidMount()
You can pull fetchBusinesses
completely out of your component:
const fetchBusinesses = () => { // or pass some additional input from component as args
return fetch("theURL", { method: "GET" }).then(n => process(n));
};
const Comp = () => {
React.useEffect(() => {
fetchBusinesses().then(someVal => {
// ... do something with someVal
});
}, []); // eslint warning solved!
return <div>{state}</div>;
};
This will not only provide a simple solution and solve the exhaustive-deps warning. fetchBusiness
now can be tested better and eases up Comp
, as it resides in module scope outside the React tree.
Relocating fetchBusinesses
outside works well here, as we would only be able to read initial props and state from the component anyway due to the stale closure scope ([]
dep in useEffect
).
useEffect
depend on this value (pure computation function)useCallback
as last resortPulling fetchBusinesses
inside useEffect()
doesn't really help, if you access other state in it. eslint would still complain: Codesandbox.
I also would keep back from eslint exhaustive-deps ignore comments. It's just to easy to forget them when you do some refactoring and overhaul of your dependencies.