react/no-set-state
Disallow this.setState in class components
If your app keeps all of its state in a store such as Redux or MobX, state inside a component is a second place where data lives, and the store doesn't know about it. This rule reports every call to this.setState in a class component or a createReactClass component.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"react/no-set-state" = "error" # or "warn"Examples#
example.jsx1 problem
class Counter extends React.Component {
increment() {
this.setStateDo not use setState({ count: this.state.count + 1 });
}
render() {
return <button onClick={() => this.increment()}>{this.state.count}</button>;
}
}example.jsxNo problems
class Counter extends React.Component {
render() {
return <button onClick={this.props.onIncrement}>{this.props.count}</button>;
}
}When not to use it#
Local state is a normal part of React. Only turn this rule on if your project has decided to keep all state outside its components. It doesn't look at the useState hook.