I'd like to have a rule to detect unused React class methods. The rule would filter out React lifecycle methods, take the other ones and check if they are used anywhere in the class itself.
Example:
class Component extends React.Component {
// error: unused method
someMethod() {
// something...
}
makeApiCall() {
// do api call...
}
handleClick() {
this.makeApiCall();
}
render() {
return (<button onClick={this.handleClick}>Do it!</button>);
}
}
The motivation behind this rule is that it's actually a bad practice to reference React.Component instance methods outside of the instance itself, so it would make sense to check if any methods inside the class are being used or are some kind of unused leftover.
You can鈥檛 possibly know it鈥檚 unused statically - anything that imports Component could reference Component.prototype.someMethod or similar.
Similarly, you never directly use, say, componentDidUpdate, but React does - and there鈥檚 no way for a general purpose linter to catch things like that.
You can鈥檛 possibly know it鈥檚 unused statically - anything that imports Component could reference Component.prototype.someMethod or similar.
I know that, but AFAIK it's not a good practice to reference React.Component static methods outside of the class component itself.
Similarly, you never directly use, say, componentDidUpdate, but React does - and there鈥檚 no way for a general purpose linter to catch things like that.
Exactly - you never directly use those and you probably shouldn't also use other component methods outside of it. Knowing this you can filter out React-specific methods (componentDidUpdate etc.) and check if other methods are used in the class itself.
I suppose that might make sense for a React class component, sure. maybe no-unused-class-component-methods
@ljharb Yeah! I'm sorry, maybe I wasn't specific enough about the request :) I've edited my first post to make it more clear.
Can i take this?
Anything with the help wanted label, without a linked PR, is always up for grabs.
I saw that recently there was no action taken regarding this topic. I prepared solution that might help. Let me know, if there is something I should fix there. https://github.com/yannickcr/eslint-plugin-react/pull/2239
@ljharb Do you have time for checking, if this PR is helpful?
This would make such a great lint rule! 鉂わ笍
It would be so wonderful to have this rule 馃檹
+1
and another +1 馃檪
+1, thx!
+1, please
There already is a separate npm plugin released for this, but unfortunately I didn't get it to work. Here it is, if somebody has better luck with it, let me know: https://www.npmjs.com/package/eslint-plugin-no-unused-react-component-methods
Most helpful comment
This would make such a great lint rule! 鉂わ笍