How to fix missing dependency warning when using useEffect React Hook?

前端 未结 13 1799
无人及你
无人及你 2020-11-22 03:14

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         


        
相关标签:
13条回答
  • 2020-11-22 03:48

    I only want to run [fetchBusinesses] once in the beginning similar to componentDidMount()

    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).

    How to omit function dependencies

    • Move function inside of effect
    • Move function outside of component - (we are using this one)
    • Call function during rendering and let useEffect depend on this value (pure computation function)
    • Add the function to effect deps and wrap it with useCallback as last resort

    Concerning other solutions:

    Pulling 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.

    0 讨论(0)
提交回复
热议问题