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

前端 未结 13 1981
无人及你
无人及你 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:44

    If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning

    useEffect(() => {
        const fetchBusinesses = () => {
           return fetch("theURL", {method: "GET"}
        )
          .then(res => normalizeResponseErrors(res))
          .then(res => {
            return res.json();
          })
          .then(rcvdBusinesses => {
            // some stuff
          })
          .catch(err => {
            // some error handling
          });
      };
      fetchBusinesses();
    }, []);
    

    If however you are using fetchBusinesses outside of render, you must note two things

    1. Is there any issue with you not passing fetchBusinesses as a method when it's used during mount with its enclosing closure?
    2. Does your method depend on some variables which it receives from its enclosing closure? This is not the case for you.
    3. On every render, fetchBusinesses will be re-created and hence passing it to useEffect will cause issues. So first you must memoize fetchBusinesses if you were to pass it to the dependency array.

    To sum it up I would say that if you are using fetchBusinesses outside of useEffect you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps otherwise you can move the method inside of useEffect

    To disable the rule you would write it like

    useEffect(() => {
       // other code
       ...
    
       // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []) 
    

提交回复
热议问题