Rules
no-access-state-in-setstate
Full Name in eslint-plugin-react-x
react-x/no-access-state-in-setstateFull Name in @eslint-react/eslint-plugin
@eslint-react/no-access-state-in-setstatePresets
xrecommendedrecommended-typescriptrecommended-type-checked
Description
Disallow accessing this.state inside setState calls.
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 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 }))}
/>
);
}
}