A state field that's set but never read still makes the component render again each time it changes, and it makes the component look like it depends on that value.
The rule collects the fields from state = { .. }, this.state = { .. } in the constructor, getInitialState, and this.setState({ .. }). It reports a field that nothing in the component reads.
Configure
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"react/no-unused-state" = "error" # or "warn"
Examples
Reported:
class Counter extends React.Component {
state = { count: 0, lastClick: null };
render() {
return <button>{this.state.count}</button>;
}
}
class Counter extends React.Component {
handleClick = () => {
this.setState({ lastClick: Date.now() });
};
render() {
return <button onClick={this.handleClick}>Click</button>;
}
}
Not reported:
class Counter extends React.Component {
state = { count: 0, lastClick: null };
render() {
const { count, lastClick } = this.state;
return <button title={lastClick}>{count}</button>;
}
}
If the whole state is spread, passed to a function, or read with a computed key, the rule can't tell which fields are used and reports nothing for that component:
class Counter extends React.Component {
state = { count: 0, lastClick: null };
render() {
return <CounterView {...this.state} />;
}
}