Skip to content

Incorrect setState usage in example #2739

Description

@panfiva

https://reactjs.org/docs/hooks-state.html#equivalent-class-example shows

render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }

However, https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous provides the following examples, indicating that we should not use this.state.count + 1 when updating state dues to async updates:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions