Skip to content

react/no-direct-mutation-state Correctness

This rule is turned on by default.

What it does

The restriction coder cannot directly change the value of this.state

Why is this bad?

calling setState() afterwards may replace the mutation you made

Example

jsx
 // error
 var Hello = createReactClass({
   componentDidMount: function() {
     this.state.name = this.props.name.toUpperCase();
   },
   render: function() {
     return <div>Hello {this.state.name}</div>;
   }
 });

 class Hello extends React.Component {
   constructor(props) {
     super(props)

     doSomethingAsync(() => {
       this.state = 'bad';
     });
   }
 }

 // success
 var Hello = createReactClass({
   componentDidMount: function() {
     this.setState({
       name: this.props.name.toUpperCase();
     });
   },
   render: function() {
     return <div>Hello {this.state.name}</div>;
   }
 });

 class Hello extends React.Component {
   constructor(props) {
     super(props)

     this.state = {
       foo: 'bar',
     }
   }
 }

How to use

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny react/no-direct-mutation-state
json
{
  "rules": {
    "react/no-direct-mutation-state": "error"
  }
}

References

Released under the MIT License.