As @gaearon has mentioned here and other places, using setState inside componenDidUpdate is acceptable, so long as it's within a conditional check.
Does it seem reasonable to allow a configuration option for this rule to allow setState usage within componenDidUpdate, so long as it's within a conditional check of some kind?
For example, this would pass here:
componentDidUpdate() {
if (!this.state.isEnabled) {
this.setState({ isEnabled: true })
}
}
but this would still fail:
componentDidUpdate() {
this.setState({ isEnabled: true })
}
An issue here would be that it's still not entirely guaranteed that more complex use cases wouldn't still end up in an infinite loop.
The comment you linked to says it has to be inside a function - not inside a conditional check.
This would be awesome. I think it's fine if it's in a conditional or if you move the setState call off to another method.
In the react docs for componentDidUpdate, it says You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition and the example is an if statement.
The condition would have to be one that prevents an infinite loop, which isn鈥檛 something that鈥檚 be statically knowable.
@ljharb true, but I still want to use this rule. Maybe I'll just change it to a warning in our codebase, but overall I prefer rules to be strict so that they cannot be committed at all.
any updates on whether this is going to be an option or not ?
Most helpful comment
In the react docs for componentDidUpdate, it says
You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a conditionand the example is an if statement.