Skip to content

Rule idea: Disallow accessing this.state within setState #943

@relekang

Description

@relekang

When using previous state in setState it can be unsafe to use this.state, because the scheduling and batching in react might result in this.state being something else than when the function was called. This might lead to race condition like a counter being set to 1, 2, 3, 3 if the two last calls are called within a batch when the expected result would be 1, 2, 3, 4.

Example

// Good this.setState((previousState) => ({ counter: previousState.counter + 1 })); // Bad this.setState({counter: this.state.counter + 1});

I am currently working on implementing a rule like that enforces using callback pattern if state is accessed within setState. Is this something that you would like to have in this plugin?

React docs on this topic

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions