Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[eslint-plugin-react-hooks] Report constant constructions (#19590)
* [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