eslint-plugin-react-perf
eslint-plugin-react-perf copied to clipboard
The linter should also warn against bad practices inside hooks
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).
Like this?
const Component = ({prop = []}) => {
useEffect(()=>{
//
}, [prop])
return <div/>
}
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];
};
It's a great idea. This should definitely be done, and I hope to get to it. Thanks
@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'
}
}
This would be a useful rule. I notice the pattern of custom hooks returning a new reference every time all too often.
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.
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.