Skip to content

Rule proposal: no-sync-state-usage-after-setstate #1648

@dmose

Description

@dmose

From the React 16.2 docs:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

In addition to this being effectively a race condition now, I would imagine that the race will get hit more often once React 16 allows for async rendering.

It would be wonderful to have a rule to flag this.

Activity

ljharb

ljharb commented on Jan 19, 2018

@ljharb
Member

We do already have https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-access-state-in-setstate.md, but it sounds like you're asking for "after", which that doesn't quite cover.

This seems reasonable, but I don't think a new rule for "after" is the right approach. Maybe a new rule for all this.state usage, that has options for "in" and "after" (and thus is extensible for anything moving forward), and deprecating the existing rule?

dmose

dmose commented on Jan 19, 2018

@dmose
Author

You're correct that I'm asking for "after" here; I'm already using the rule you cited to handle "in". Assuming that both "in" and "after" can be used together, your proposal sounds good to me.

dmose

dmose commented on Jan 19, 2018

@dmose
Author

Maybe the new rule wants to be called "no-race-with-setstate"?

vince1995

vince1995 commented on Nov 29, 2022

@vince1995

Any progress on this? After a React update some Components were buggy because they used a state which was set previously in the same function. In the previous React version they worked fine.

Now I want to prevent me and my colleagues from writing code like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @ljharb@dmose@vince1995

        Issue actions

          Rule proposal: no-sync-state-usage-after-setstate · Issue #1648 · jsx-eslint/eslint-plugin-react