-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Open
Description
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 commentedon Jan 19, 2018
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 commentedon Jan 19, 2018
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 commentedon Jan 19, 2018
Maybe the new rule wants to be called "no-race-with-setstate"?
vince1995 commentedon Nov 29, 2022
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.