Skip to content

Commit

Permalink
[eslint-plugin-react-hooks] Report constant constructions (#19590)
Browse files Browse the repository at this point in the history
* [eslint-plugin-react-cooks] Report constant constructions

The dependency array passed to a React hook can be thought of as a list of cache keys. On each render, if any dependency is not `===` its previous value, the hook will be rerun. Constructing a new object/array/function/etc directly within your render function means that the value will be referentially unique on each render. If you then use that value as a hook dependency, that hook will get a "cache miss" on every render, making the dependency array useless.

This can be especially dangerous since it can cascade. If a hook such as `useMemo` is rerun on each render, not only are we bypassing the option to avoid potentially expensive work, but the value _returned_ by `useMemo` may end up being referentially unique on each render causing other downstream hooks or memoized components to become deoptimized.

* Fix/remove existing tests

* Don't give an autofix of wrapping object declarations

It may not be safe to just wrap the declaration of an object, since the object may get mutated.

Only offer this autofix for functions which are unlikely to get mutated.

Also, update the message to clarify that the entire construction of the value should get wrapped.

* Handle the long tail of nodes that will be referentially unique

* Catch let/var constant constructions on initial assignment

* Trim trailing whitespace

* Address feedback from @gaearon

* Rename "assignment" to "initialization"

* Add test for a constant construction used in multiple dependency arrays
  • Loading branch information
captbaritone committed Aug 13, 2020
1 parent dab0854 commit 1d5e10f
Show file tree
Hide file tree
Showing 2 changed files with 773 additions and 116 deletions.

0 comments on commit 1d5e10f

Please sign in to comment.