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

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

    You can set it directly as the useEffect callback:

    useEffect(fetchBusinesses, [])
    

    It will trigger only once, so make sure all the function's dependencies are correctly set (same as using componentDidMount/componentWillMount...)


    Edit 02/21/2020

    Just for completeness:

    1. Use function as useEffect callback (as above)

    useEffect(fetchBusinesses, [])
    

    2. Declare function inside useEffect()

    useEffect(() => {
      function fetchBusinesses() {
        ...
      }
      fetchBusinesses()
    }, [])
    

    3. Memoize with useCallback()

    In this case, if you have dependencies in your function, you will have to include them in the useCallback dependencies array and this will trigger the useEffect again if the function's params change. Besides, it is a lot of boilerplate... So just pass the function directly to useEffect as in 1. useEffect(fetchBusinesses, []).

    const fetchBusinesses = useCallback(() => {
      ...
    }, [])
    useEffect(() => {
      fetchBusinesses()
    }, [fetchBusinesses])
    

    4. Disable eslint's warning

    useEffect(() => {
      fetchBusinesses()
    }, []) // eslint-disable-line react-hooks/exhaustive-deps
    

提交回复
热议问题