Expand Minimize

Don't call 'setState' in the specific lifecycle methods

Don't call 'setState' in the specific lifecycle methods

CheckId RCT010116
TypeName StateUpdateRule
Severity Error
Type React component

You shouldn't call setState in the following methods:

  • constructor
  • getDefaultProps
  • getInitialState
  • render
  • componentWillUnmount

Updating state using the setState method in these methods will either not update the state or cause an infinite loop.

Bad practice (setState called in render causing an infinite loop)

export class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: "Steve" };
    }

    render() {
        this.setState({ name: "Joe" });
        return <div>Hello {this.state.name}</div>;
    }
}


Good practice (updating state defined in a separate lifecycle method)

export class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: "Steve" };
    }

    componentWillMount() {
        this.setState({ name: "Joe" });
    }

    render() {
        return <div>Hello {this.state.name}</div>;
    }
}

Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.