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