Assignment should not be made to this.state in the React 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 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. componentWillMount()
  6. componentWillReceiveProps()
  7. componentDidCatch()
  8. UNSAFE_componentWillMount()
  9. 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.handleChanged = this.handleChanged.bind(this);
    }
    handleChanged() {
        this.state = { message: "Hello" }; // REACT_DIRECT_ASSIGN_TO_STATE alarm
        alert(this.state.message);
    }
    render() {
        return (
            <button onClick={this.handleChanged}>Click!</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.handleChanged = this.handleChanged.bind(this);
    }
    handleChanged() {
        this.setState({ message: "Hello" });
        alert(this.state.message);
    }
    render() {
        return (
            <button onClick={this.handleChanged}>Click!</button>
        );
    }
}

Version

This rule was introduced in DeepScan 1.2.0-alpha.

Was this documentation helpful?