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

  • REACT_BAD_INITIAL_STATE_TYPE
  • Error
  • Medium
  • 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 outputs a warning message.

Noncompliant Code Example

View with compliant examples side by side
import React from 'react';

export 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

View with noncompliant examples side by side
import React from 'react';

export 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 Warning: Hello.state: must be set to an object or null

Was this documentation helpful?