Expand Minimize

Don't override React component methods supported only in createReactClass() in ES6 class component

When building ES6 class components, don't override React component methods that are supported only in the 'createReactClass' API

CheckId RCT010108
TypeName ReactComponentMethodRule
Severity Error
Type React component

When building ES6 class components, don't override React component methods that are supported only in the createReactClass API. When used in ES6 class components, these methods can lead to side-effects because the intended initialization might not have been applied.

Bad practice (getInitialState used in an ES6 class component)

export class Greeting extends React.Component {
    getInitialState() {
        return { name: 'Steve' };
    }

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


Good practice (state initialization done in ES6 class component's constructor)
export class Greeting extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name: 'Steve' };
    }

    render() {
        return <div>Hi {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.