Updating the state inside the specific lifecycle methods of a React class component should be avoided

  • REACT_BAD_UPDATE_STATE
  • Error
  • Medium
  • react

This rule applies when the state is updated inside the specific lifecycle methods of a React class component.

It is not allowed to use setState() or assign to this.state inside the following methods:

  1. constructor() (setState() is not allowed, but this.state assignment is possible)
  2. render()
  3. componentWillUnmount()

If the state is updated inside the above methods, React does not apply the updated state or it may cause an unintentional behavior even though the update is applied. For example, calling setState() inside render() can cause an infinite loop with render().

Noncompliant Code Example

View with compliant examples side by side
import React from 'react';

export default class SayHello extends React.Component {
  constructor(props) {
    super(props);
    this.setState({ name: "DeepScan" }); // REACT_BAD_UPDATE_STATE alarm becuase 'setState()' is not allowed in constructor.
  }
  render() {
    this.setState({ name: this.state.name + " Hello" }); // REACT_BAD_UPDATE_STATE alarm because 'render()' should be a pure function of props and state.
    return <div>{this.state.name}</div>;
  }
}

Compliant Code Example

View with noncompliant examples side by side
import React from 'react';

export default class SayHello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "DeepScan" };
  }
  componentDidMount() {
    this.setState({ name: this.state.name + " Hello" });
  }
  render() {
    return <div>{this.state.name}</div>;
  }
}

Version

This rule was introduced in DeepScan 1.3.0-beta.

See

  • React Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the SayHello component.

  • React Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

Was this documentation helpful?