jsx-eslint / eslint-plugin-react

React-specific linting rules for ESLint
MIT License
8.88k stars 2.76k forks source link

New rule: memoize-funcs #2279

Open hornta opened 5 years ago

hornta commented 5 years ago

This rule can take a string option "always" or "never". It will report when memoizing a function in either useMemo or useCallback depending on the option. I would want the default option to be "never"

never

Example of incorrect code

/* eslint no-cond-assign: ["error", "never"] */
function Foo() {
  useMemo(() => () => { ... }, [ ... ]);
  ...
}

Example of correct code

/* eslint no-cond-assign: ["error", "never"] */
function Foo() {
  useCallback(() => { ... }, [ ... ]);
  ...
}

always

Example of incorrect code

/* eslint no-cond-assign: ["error", "always"] */
function Foo() {
  useCallback(() => { ... }, [ ... ]);
  ...
}

Example of correct code

/* eslint no-cond-assign: ["error", "always"] */
function Foo() {
  useMemo(() => () => { ... }, [ ... ]);
  ...
}
ljharb commented 5 years ago

Can you elaborate on the reasoning?

If hooks aren't available, a linter rule wouldn't be needed; if they are available, when would it be a problem to use them?

hornta commented 5 years ago

I believe it's only about consistency. There's probably a good reason React added useCallback hook as a thin wrapper on top of useMemo. I wouldn't want to see useMemo(() => () => { ... }) in my code if useCallback is available for just that reason, to memoize functions.

ljharb commented 5 years ago

That use case seems like a good one for eslint-plugin-react-hooks, since the react team is maintaining that.