Rules
no-direct-mutation-state
Full Name in @eslint-react/eslint-plugin
@eslint-react/no-direct-mutation-stateFull Name in eslint-plugin-react-x
react-x/no-direct-mutation-statePresets
x
recommended
recommended-typescript
recommended-type-checked
strict
strict-typescript
strict-type-checked
Description
Disallow direct mutation of this.state.
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
The only place that's acceptable to assign this.state is in a class component's constructor.
Examples
Failing
import React from "react";
interface MyComponentProps {}
interface MyComponentState {
foo: string;
}
class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
state = {
foo: "bar",
};
render() {
return (
<div
onClick={() => {
this.state.foo = "baz";
// ^^^^^^^^^^^^^^^^^
// - Do not mutate state directly. Use 'setState()' instead.
}}
>
{this.state.foo}
</div>
);
}
}Passing
import React from "react";
interface MyComponentProps {}
interface MyComponentState {
foo: string;
}
class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
state = {
foo: "bar",
};
render() {
return (
<div
onClick={() => {
this.setState({ foo: "baz" });
}}
>
{this.state.foo}
</div>
);
}
}