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

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

    The solution is also given by react, they advice you use useCallback which will return a memoize version of your function :

    The 'fetchBusinesses' function makes the dependencies of useEffect Hook (at line NN) change on every render. To fix this, wrap the 'fetchBusinesses' definition into its own useCallback() Hook react-hooks/exhaustive-deps

    useCallback is simple to use as it has the same signature as useEffect the difference is that useCallback returns a function. It would look like this :

     const fetchBusinesses = useCallback( () => {
            return fetch("theURL", {method: "GET"}
        )
        .then(() => { /* some stuff */ })
        .catch(() => { /* some error handling */ })
      }, [/* deps */])
      // We have a first effect thant uses fetchBusinesses
      useEffect(() => {
        // do things and then fetchBusinesses
        fetchBusinesses(); 
      }, [fetchBusinesses]);
       // We can have many effect thant uses fetchBusinesses
      useEffect(() => {
        // do other things and then fetchBusinesses
        fetchBusinesses();
      }, [fetchBusinesses]);
    

提交回复
热议问题