no-unused-state
state = {
id: null,
name: '',
age: 0,
}
const {
id,
...data
} = this.state;
console.log('data', data);
name and age should not be reported as error [eslint] Unused state field: 'departmentId' (react/no-unused-state).
Using spread here offers only two options:
Which would be more useful?
Dunno which one is actually more useful, it's a hard choice as each approach has some serious drawbacks/tradeoffs.
Just pasting in other (although similar) pattern causing "false positives" for this this rule:
class App extends React.Component {
constructor() {
super();
this.state = {
a: spring(0),
};
}
render() {
return (
<Motion style={this.state}>
{a => {
count.push(a);
return null;
}}
</Motion>
);
}
}
In that case, passing this.props or this.state anywhere is a massive antipattern; so doing it should be very inconvenient.
@ljharb "use an override comment" is nice. But I do not know this usage.
How to use JSDoc to comment id and data?
const {
id,
...data
} = this.state;
JSDoc has nothing to do with anything.
In this case, you'd add // eslint-disable-line react/no-unused-state on the line that was warning.
@ljharb This is not elegant, but only so. Thanks.
In the case of spread, I would argue that (2) is more useful. In such cases, a typechecker with an exact object type should be used to prevent extraneous properties.
Note that {...this.state} also already silences the rule.
Note that {...this.state} also already silences the rule.
Given that, it seems that option 2 is indeed the proper direction.
I have to agree with option #2 in the least. My problem is I am rendering a component from a function:
{getComponent(this.state)}
And the rule goes haywire at that point. I guess I could make getComponent a class method and then the rule works, but that makes my code less clean (React is supposed to be functional-friendly).
I may need to turn off this rule, which is unfortunate, because most of the time, it is a big help and has caught some needless state.
I鈥檇 suggest making it an SFC instead and using jsx rather than a function call (renderFoo class methods are an antipattern).
Most helpful comment
Given that, it seems that option 2 is indeed the proper direction.