no-direct-mutation-state
Rule category
Correctness.
What it does
Disallows direct mutation of this.state
.
Why is this bad?
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 ExampleProps {}
interface ExampleState {
foo: string;
}
class Example extends React.Component<ExampleProps, ExampleState> {
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 ExampleProps {}
interface ExampleState {
foo: string;
}
class Example extends React.Component<ExampleProps, ExampleState> {
state = {
foo: "bar",
};
render() {
return (
<div
onClick={() => {
this.setState({ foo: "baz" });
}}
>
{this.state.foo}
</div>
);
}
}