Assignment should not be made to this.state in the React class component's specific methods
- REACT_DIRECT_ASSIGN_TO_STATE
 - Error
 - Medium
 - react
 
This rule applies when assignment is made to this.state in the React class component's specific methods.
When updating this.state inside the following methods, you should use setState():
- DOM event handler
 componentDidMount()componentDidUpdate()shouldComponentUpdate()componentDidCatch()UNSAFE_componentWillMount()UNSAFE_componentWillReceiveProps()
If this.state is modified directly inside the above methods, it may cause a problem because the component is not re-rendered or the updated state is no applied.
Noncompliant Code Example
View with compliant examples side by sideimport React from 'react';
export class SayHello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: 'Hello' };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.state = { message: 'Bye' }; // REACT_DIRECT_ASSIGN_TO_STATE alarm
  }
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.message}
      </button>
    );
  }
}Compliant Code Example
View with noncompliant examples side by sideimport React from 'react';
export class SayHello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: 'Hello' };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({ message: 'Bye' });
  }
  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.message}
      </button>
    );
  }
}Version
This rule was introduced in DeepScan 1.2.0-alpha.