3

In a React Native useEffect it is acceptable to use an empty dependency array (and this is often done intentionally for legitimate reasons).

In useEffect, what's the difference between providing no dependency array and an empty one?

Yet Linter keeps complaining and suggesting to either add certain parameters as elements of the dependency array or to remove it. Removing the dependency array is not an option for me. Should I accept the Linter suggestion and add a long list of items to the dependency array? Or is there an easy way I change the Linter settings?

ahron
  • 803
  • 6
  • 29

2 Answers2

6

AFAIK there's no configuration to the react-hooks/exhaustive-deps linting rule, but you can ignore the eslint rule for a specific line.

If you truly want the effect to run only once exactly when the component mounts then you are correct to use an empty dependency array. You can disable the eslint rule for that line to ignore it.

useEffect(() => {
  ... business logic ...

  // NOTE: Run effect once on component mount, please
  // recheck dependencies if effect is updated.
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Note: If you later update the effect and it needs to run after other dependencies then this disabled comment can potentially mask future bugs, so I suggest leaving a rather overt comment as for the reason to override the established linting rule.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
1

Usually what linter suggests (adding the dependencies) is the best solution for it, since usually you'll want to re-run the effect when some of those variables used in the effect change. See https://typeofnan.dev/you-probably-shouldnt-ignore-react-hooks-exhaustive-deps-warnings/ for more info. Also it has been discussed here: https://github.com/facebook/react/issues/14920

mihai1990
  • 632
  • 5
  • 20