noReactDirectStateMutation (JavaScript)
Language JavaScript (and super languages)
Summary
Section titled “Summary”- Diagnostic Category:
lint/nursery/noReactDirectStateMutation - This rule doesn’t have a fix.
- The default severity of this rule is error.
- This rule belongs to the following domains:
- Sources:
- Inspired from
react/no-direct-mutation-state - Inspired from
react-x/no-direct-mutation-state - Inspired from
@eslint-react/no-direct-mutation-state
- Inspired from
How to configure
Section titled “How to configure”{ "linter": { "rules": { "nursery": { "noReactDirectStateMutation": "error" } } }}Description
Section titled “Description”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.
Examples
Section titled “Examples”Invalid
Section titled “Invalid”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 }); }}Related links
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.