Rules
no-access-state-in-setstate
Full Name in @eslint-react/eslint-plugin
@eslint-react/no-access-state-in-setstateFull Name in eslint-plugin-react-x
react-x/no-access-state-in-setstatePresets
x
recommended
recommended-typescript
recommended-type-checked
strict
strict-typescript
strict-type-checked
Description
Disallows accessing this.state inside setState calls.
Using this.state inside setState calls might result in errors when two state updates are batched, causing references to the old state rather than the current state.
Examples
Failing
import React from "react";
interface MyComponentProps {}
interface MyComponentState {
foo: number;
}
class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
state = {
foo: 1,
};
render() {
return (
<button onClick={() => this.setState({ foo: this.state.foo + 1 })} />
// ^^^^^^^^^^^^^^
// - Do not access 'this.state' within 'setState'. Use the update function instead.
);
}
}Passing
import React from "react";
interface MyComponentProps {}
interface MyComponentState {
foo: number;
}
class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
state = {
foo: 1,
};
render() {
return (
<button
onClick={() => this.setState((state) => ({ foo: state.foo + 1 }))}
/>
);
}
}