state-in-constructor
Added in v0.9.4Configuration
Rule details
Enforce a consistent place to initialize state in React class components.
The rule does not require components to declare state and does not provide automatic fixes.
Options
"always"(default): Initialize state in the constructor."never": Initialize state with a class field.
Examples of incorrect code for the default "always" option:
Examples of correct code for the default "always" option:
With "never", the constructor assignment above is incorrect. Use the class field instead:
Examples of correct code with "never":
The "always" mode ignores static fields. Both modes apply only to recognized React class components.
Settings
The rule supports settings.react.pragma and @jsx annotations when identifying React class components.
Differences from upstream
rslint intentionally differs from eslint-plugin-react 7.37.5 in these cases:
- Public string and static template keys, such as
['state']and[`state`], are checked just like.state. Private#stateand dynamic keys are ignored. For example, withconst state = 'other',[state]initializesotherand is not reported. Variable values and template substitutions are not resolved. - With
"never", assignments must use a component constructor'sthis. Arrow functions retain thatthis; ordinary functions, nested class methods, field initializers, and static blocks have their ownthisand are not attributed to an outer constructor. - A private superclass such as
React.#ComponentorReact.#PureComponentdoes not identify a React component. - Static superclass keys such as
React['Component']andReact[`PureComponent`]identify React components. Variable keys such asReact[Component]are ignored: withconst Component = 'Other', the superclass isReact.Other.
For example, with "never", only the arrow's assignment is reported:
When not to use it
Disable this rule if your project allows both initialization styles.