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():

  1. DOM event handler
  2. componentDidMount()
  3. componentDidUpdate()
  4. shouldComponentUpdate()
  5. componentDidCatch()
  6. UNSAFE_componentWillMount()
  7. 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 side
import 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 side
import 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.

Was this documentation helpful?