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 {
ExampleState.foo: stringfoo: string;
}
class class ExampleExample extends React.class React.Component<P = {}, S = {}, SS = any>Component<ExampleProps, ExampleState> {
Example.state: {
foo: string;
}
state = {
foo: stringfoo: "bar",
};
Example.render(): React.JSX.Elementrender() {
return (
<JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div
React.DOMAttributes<HTMLDivElement>.onClick?: React.MouseEventHandler<HTMLDivElement> | undefinedonClick={() => {
this.Example.state: {
foo: string;
}
state.foo: stringfoo = "baz";
// - Do not mutate state directly. Use 'setState()' instead.
}}
>
{this.Example.state: {
foo: string;
}
state.foo: stringfoo}
</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
);
}
}Passing
import React from "react";
interface ExampleProps {}
interface ExampleState {
ExampleState.foo: stringfoo: string;
}
class class ExampleExample extends React.class React.Component<P = {}, S = {}, SS = any>Component<ExampleProps, ExampleState> {
Example.state: {
foo: string;
}
state = {
foo: stringfoo: "bar",
};
Example.render(): React.JSX.Elementrender() {
return (
<JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div
React.DOMAttributes<HTMLDivElement>.onClick?: React.MouseEventHandler<HTMLDivElement> | undefinedonClick={() => {
this.React.Component<ExampleProps, ExampleState, any>.setState<"foo">(state: ExampleState | ((prevState: Readonly<ExampleState>, props: Readonly<ExampleProps>) => Pick<ExampleState, "foo"> | ExampleState | null) | Pick<...> | null, callback?: (() => void) | undefined): voidsetState({ foo: stringfoo: "baz" });
}}
>
{this.Example.state: {
foo: string;
}
state.foo: stringfoo}
</JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
);
}
}