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

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

    Actually the warnings are very useful when you develop with hooks. but in some cases, it can needle you. especially when you do not need to listen for dependencies change.

    If you don't want to put fetchBusinesses inside the hook's dependencies, you can simply pass it as an argument to the hook's callback and set the main fetchBusinesses as the default value for it like this

    useEffect((fetchBusinesses = fetchBusinesses) => {
       fetchBusinesses();
    }, []);
    

    It's not best practice but it could be useful in some cases.

    Also as Shubnam wrote, you can add below code to tell ESLint to ignore the checking for your hook.

    // eslint-disable-next-line react-hooks/exhaustive-deps
    

提交回复
热议问题