logoESLint React
Rules

no-direct-mutation-state

Disallows direct mutation of 'this.state'.

Full Name in eslint-plugin-react-x

react-x/no-direct-mutation-state

Full Name in @eslint-react/eslint-plugin

@eslint-react/no-direct-mutation-state

Presets

x recommended recommended-typescript recommended-type-checked strict strict-typescript strict-type-checked

Rule Details

Never mutate this.state directly, as calling setState() afterward may replace the mutation you made. Treat this.state as if it were immutable.

The only place it's acceptable to assign this.state is in a class component's constructor.

Common Violations

Invalid

import React from "react";

interface MyComponentProps {}

interface MyComponentState {
  foo: string;
}

class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
  state = {
    foo: "bar",
  };

  render() {
    return (
      <div
        onClick={() => {
          this.state.foo = "baz";
          //   ^^^ Do not mutate state directly. Use 'setState()' instead.
        }}
      >
        {this.state.foo}
      </div>
    );
  }
}

Valid

import React from "react";

interface MyComponentProps {}

interface MyComponentState {
  foo: string;
}

class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
  state = {
    foo: "bar",
  };

  render() {
    return (
      <div
        onClick={() => {
          this.setState({ foo: "baz" });
        }}
      >
        {this.state.foo}
      </div>
    );
  }
}

Resources


See Also

On this page