Skip to content

noReactDirectStateMutation (JavaScript)

Language JavaScript (and super languages)
biome.json
{
"linter": {
"rules": {
"nursery": {
"noReactDirectStateMutation": "error"
}
}
}
}

Disallow mutating this.state directly in React class components.

State should only be updated through this.setState() so React can correctly schedule a re-render and combine state updates. Writing to this.state is only allowed in the constructor of a class component, to set the initial state. This rule applies to classes that extend Component or PureComponent, including React.Component and React.PureComponent.

class Counter extends React.Component {
increment() {
this.state.count = this.state.count + 1;
}
}
code-block.jsx:3:5 lint/nursery/noReactDirectStateMutation ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✖ This code changes this.state directly.

1 │ class Counter extends React.Component {
2 │ increment() {
> 3 │ this.state.count = this.state.count + 1;
│ ^^^^^^^^^^^^^^^^
4 │ }
5 │ }

ℹ React does not render the component again after a direct change, and a later setState() call can overwrite it.

ℹ Call this.setState() instead. Only assign to this.state directly in the constructor, to set the initial state.

ℹ This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

class Counter extends React.Component {
constructor(props) {
super(props);
loadCount((count) => {
this.state = { count };
});
}
}
code-block.jsx:5:7 lint/nursery/noReactDirectStateMutation ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✖ This code changes this.state directly.

3 │ super(props);
4 │ loadCount((count) => {
> 5 │ this.state = { count };
│ ^^^^^^^^^^
6 │ });
7 │ }

ℹ React does not render the component again after a direct change, and a later setState() call can overwrite it.

ℹ Call this.setState() instead. Only assign to this.state directly in the constructor, to set the initial state.

ℹ This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment() {
this.setState({ count: this.state.count + 1 });
}
}