Rules
no-access-state-in-setstate

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: numberfoo: number;
}
 
class class ExampleExample extends React.class React.Component<P = {}, S = {}, SS = any>Component<ExampleProps, ExampleState> {
  
Example.state: {
    foo: number;
}
state
= {
foo: numberfoo: 1, }; Example.render(): React.JSX.Elementrender() { return ( <JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>button React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | 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: numberfoo: this.
Example.state: {
    foo: number;
}
state
.foo: numberfoo
+ 1 })} />
// - Do not access 'this.state' within 'setState', use 'setState' callback instead. ); } }

Passing

import React from "react";
 
interface ExampleProps {}
 
interface ExampleState {
  ExampleState.foo: numberfoo: number;
}
 
class class ExampleExample extends React.class React.Component<P = {}, S = {}, SS = any>Component<ExampleProps, ExampleState> {
  
Example.state: {
    foo: number;
}
state
= {
foo: numberfoo: 1, }; Example.render(): React.JSX.Elementrender() { return ( <JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>button React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefinedonClick={() => 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): voidsetState((state: Readonly<ExampleState>state) => ({ ExampleState.foo: numberfoo: state: Readonly<ExampleState>state.foo: numberfoo + 1 }))} /> ); } }