Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add state-in-constructor rule #1945

Merged
merged 9 commits into from
Jan 21, 2019
Prev Previous commit
Next Next commit
Add doc for state-in-constructor rule
  • Loading branch information
lukyth committed Aug 18, 2018
commit 4706e8696edaedc122eb138885de50c6c967c52c
74 changes: 74 additions & 0 deletions docs/rules/state-in-constructor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Enforce state initialization style (react/state-in-constructor)

This rule will enforce the state initialization style to be either in a constructor or with a class property.

## Rule Options

```js
...
"react/state-in-constructor": [<enabled>, <mode>]
...
```

### `always` mode

Will enforce the state initialization style to be in a constructor. This is the default mode.

The following patterns are considered warnings:

```jsx
class Foo extends React.Component {
state = { bar: 0 }
render() {
return <div>Foo</div>
}
}
```

The following patterns are **not** considered warnings:

```jsx
class Foo extends React.Component {
constructor(props) {
super(props)
this.state = { bar: 0 }
}
render() {
return <div>Foo</div>
}
}
```

### `never` mode

Will enforce the state initialization style to be with a class property.

The following patterns are considered warnings:

```jsx
class Foo extends React.Component {
constructor(props) {
super(props)
this.state = { bar: 0 }
}
render() {
return <div>Foo</div>
}
}
```

The following patterns are **not** considered warnings:

```jsx
class Foo extends React.Component {
state = { bar: 0 }
render() {
return <div>Foo</div>
}
}
```


## When Not To Use It

When the way a component state is being initialized doesn't matter.