The initial state of React component should be set to an object or null

  • REACT_BAD_INITIAL_STATE_TYPE
  • Error
  • High
  • react

This rule applies when the type of the initial state of React component is not object or null.

When the type of the initial state is not object or null in the ES6 class component constructor, React will throw an exception.

Noncompliant Code Example

import React from 'react';

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.state = "World"; // REACT_BAD_INITIAL_STATE_TYPE alarm because the type of state is string.
    }
    render() {
        return <h1>Hello, {this.state}!</h1>;
    }
}

Compliant Code Example

import React from 'react';

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.state = {name: "World"};
    }
    render() {
        return <h1>Hello, {this.state.name}!</h1>;
    }
}

Version

This rule was introduced in DeepScan 1.6.0-beta.

See

  • React Error: Hello.state: must be set to an object or null