no-access-state-in-setstate
Rule category
Correctness.
What it does
Disallows accessing this.state
inside setState
calls.
Why is this bad?
Usage of this.state
inside setState
calls might result in errors when two state calls are called in batch and thus referencing old state and not the current state.
Examples
Failing
import React from "react";
interface ExampleProps {}
interface ExampleState {
ExampleState.foo: number
foo: number;
}
class class Example
Example extends React.class React.Component<P = {}, S = {}, SS = any>
Component<ExampleProps, ExampleState> {
Example.state: {
foo: number;
}
state = {
foo: number
foo: 1,
};
Example.render(): React.JSX.Element
render() {
return (
<JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
button React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | 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: number
foo: this.Example.state: {
foo: number;
}
state.foo: number
foo + 1 })} />
// - Do not access 'this.state' within 'setState', use 'setState' callback instead.
);
}
}
Passing
import React from "react";
interface ExampleProps {}
interface ExampleState {
ExampleState.foo: number
foo: number;
}
class class Example
Example extends React.class React.Component<P = {}, S = {}, SS = any>
Component<ExampleProps, ExampleState> {
Example.state: {
foo: number;
}
state = {
foo: number
foo: 1,
};
Example.render(): React.JSX.Element
render() {
return (
<JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
button
React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined
onClick={() => this.React.Component<ExampleProps, ExampleState, any>.setState<never>(state: ExampleState | ((prevState: Readonly<ExampleState>, props: Readonly<ExampleProps>) => Pick<ExampleState, never> | ExampleState | null) | Pick<...> | null, callback?: (() => void) | undefined): void
setState((state: Readonly<ExampleState>
state) => ({ ExampleState.foo: number
foo: state: Readonly<ExampleState>
state.foo: number
foo + 1 }))}
/>
);
}
}