DocumentationRulesno-access-state-in-setstate

no-access-state-in-setstate

Rule category

Correctness.

What it does

Disallows accessing this.state inside setState calls.

Why is this bad?

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 ExampleProps {}
 
interface ExampleState {
  foo: number;
}
 
class Example extends React.Component<ExampleProps, ExampleState> {
  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 ExampleProps {}
 
interface ExampleState {
  foo: number;
}
 
class Example extends React.Component<ExampleProps, ExampleState> {
  state = {
    foo: 1,
  };
 
  render() {
    return (
      <button
        onClick={() => this.setState((state) => ({ foo: state.foo + 1 }))}
      />
    );
  }
}