Rules
no-access-state-in-setstate
Disallows accessing 'this.state' inside 'setState' calls.
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
x
recommended
recommended-typescript
recommended-type-checked
strict
strict-typescript
strict-type-checked
Rule Details
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.
Common Violations
Invalid
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.
);
}
}Valid
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 }))}
/>
);
}
}Resources
See Also
react-x/no-direct-mutation-state
Disallows direct mutation ofthis.state.react-x/no-set-state-in-component-did-mount
Disallows callingthis.setStateincomponentDidMountoutside functions such as callbacks.react-x/no-unused-state
Warns about unused class component state.