Updating the state inside the specific lifecycle methods of a React 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 component.

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

  1. constructor() (Calling setState() raises a warning message and does not update the state)
  2. getDefaultProps()
  3. getInitialState()
  4. render()
  5. 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 the infinite loop with render().

Noncompliant Code Example

import React from 'react';

class SayHello extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: "DeepScan" };
    }
    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

import React from 'react';

class SayHello extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: "DeepScan" };
    }
    componentWillMount() {
        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: setState(…): Cannot update during an existing state transition (such as within render or another component's constructor).