Expand Minimize

React lifecycle method doesn't return a valid value

React lifecycle methods must return correct values

CheckId RCT010107
TypeName LifeCycleMethodsReturnValuesRule
Severity Error
Type React component

React lifecycle methods must return correct values. Otherwise, you can either experience runtime errors or the returned value will be ignored.

Following lifecycle methods must return values of the specific type:

  • render must return React element, array, fragment, portal, string, number, boolean or null
  • getInitialState must return Object or null
  • shouldComponentUpdate must return a truthy or a falsy value
  • getSnapshotBeforeUpdate must return any value other than undefined
  • getDerivedStateFromProps must return any value other than undefined
  • callback passed as the first argument of React.useEffect must return a function or undefined
  • callback passed as the first argument of React.forwardRef must return React element, array, fragment, portal, string, number, boolean or null
  • callback passed as the first argument of React.lazy must return dynamic import

Following lifecycle methods shouldn't return any value:

  • componentWillMount
  • componentDidMount
  • componentWillReceiveProps
  • componentWillUpdate
  • componentDidUpdate
  • componentWillUnmount
  • componentDidCatch
  • callback passed as the first argument of forceUpdate
  • callback passed as the second argument of setState

Bad practice (nothing returned in render if no name specified)
export class Greeting extends React.Component {
    render() {
        if (!this.props.name) {
            return;
        }

        return <div>Hi {this.props.name}</div>;
    }
}


Bad practice (missing return keyword in render)
export class Greeting extends React.Component {
    render() {
        <div>Hi {this.props.name}</div>;
    }
}


Good practice (returns null in render if no name specified)
export class Greeting extends React.Component {
    render() {
        if (!this.props.name) {
            return null;
        }

        return <div>Hi {this.props.name}</div>;
    }
}


Good practice
export class Greeting extends React.Component {
    render() {
        return <div>Hi {this.props.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.