Understanding the React Hooks 'exhaustive-deps' lint rule

前端 未结 2 2024
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 00:17

I\'m having a hard time understanding the \'exhaustive-deps\' lint rule.

I already read this post and this post but I could not find an answer.

Here is a simpl

2条回答
  •  -上瘾入骨i
    2020-12-11 00:44

    The main purpose of the exhaustive-deps warning is to prevent the developers from missing dependencies inside their effect and lost some behavior.

    Dan abramov – developer on Facebook core – strongly recommend to keep that rule enabled.

    For the case of passing functions as dependencies, there is a dedicated chapter in the React FAQ:

    https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies

    tl;dr

    If you have to put a function inside your dependencies array:

    • Put the function outside of your component, so you are sure that the reference won't be changed on each render.
    • If you can, call the function outside of your effect, and just use the result as dependency.
    • If the function must be declared in your component scope, you have to memoize the function reference by using the useCallback hook. The reference will be changed only if the dependencies of the callback function change.

提交回复
热议问题