logoESLint React
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-setstate

Full Name in @eslint-react/eslint-plugin

@eslint-react/no-access-state-in-setstate

Presets

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

On this page