eslint-plugin-react-perf icon indicating copy to clipboard operation
eslint-plugin-react-perf copied to clipboard

The linter should also warn against bad practices inside hooks

Open SRachamim opened this issue 5 years ago • 7 comments

I expect the lint to also work inside React hooks functions:

Every hook function (which is a function named use* should not constantly return a new reference (which is an object/function/array/JSX which is not created outside the hook nor inside a useMemo/useCallback).

SRachamim avatar Jan 21 '20 11:01 SRachamim

Like this?

const Component = ({prop = []}) => {
 useEffect(()=>{
    //
  }, [prop])
 return <div/>
}

cvazac avatar Jan 23 '20 03:01 cvazac

Like this:

// should pass
// const val = {};

// should pass
// const setVal = () => /* ... */;

const useSomething = () => {
  // should fail
  // const val = {};

  // should pass
 const val = React.useMemo(() => {}, []);

  // should fail
  // const setVal = () => /* ... */;

  // should pass
  const setVal = React.useCallback(() => /* ... */, []);
  
  return [val, setVal];
};

SRachamim avatar Jan 23 '20 08:01 SRachamim

It's a great idea. This should definitely be done, and I hope to get to it. Thanks

cvazac avatar Oct 29 '20 02:10 cvazac

@cvazac I've run into a very similar situation which I hope can also be solved. Essentially the same issue, but any regular function (non-hook) that returns an object, array or function seems to be a workaround for the linting rules. We implemented the 4 recommended rules and I saw this kind of code slip through.

This is a contrived example but it's essentially what I saw in our codebase after implementing the recommended lint rules.

function Component() {

    const value1 = getChildValue();

    const value2 = {
        foo: 'bar'
    };

    return (
        <>
            <Child value={value1} /> // <-- does not violate linting rule
            <Child value={value2} /> // <-- violates linting rule
        </>
    );
}

function getChildValue() {
    return {
        foo: 'bar'
    }
}

jmancherje avatar Dec 01 '20 18:12 jmancherje

This would be a useful rule. I notice the pattern of custom hooks returning a new reference every time all too often.

bolatovumar avatar Dec 11 '20 22:12 bolatovumar

If this is implemented, would it produce a warning or an error? After reading some articles on the subject, I get the impression that useMemo and useCallback can sometimes be slower than the cost of re-declaring.

FPDK avatar Feb 20 '21 17:02 FPDK

If this is implemented, would it produce a warning or an error? After reading some articles on the subject, I get the impression that useMemo and useCallback can sometimes be slower than the cost of re-declaring.

@FPDK you can always configure whether something is an error or a warning yourself.

bolatovumar avatar Feb 21 '21 18:02 bolatovumar