react/no-will-update-set-state
Disallow this.setState in componentWillUpdate
React calls componentWillUpdate right before it renders an update. Calling this.setState there starts another update before the current one is done, and the component can end up updating forever.
The rule checks UNSAFE_componentWillUpdate too.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"react/no-will-update-set-state" = "error" # or "warn"Every option, set to its default. The ones that are commented out are unset by default.
bunfig.toml
[lint.rules]
"react/no-will-update-set-state" = [
"error",
# "disallow-in-func",
]Examples#
example.jsx1 problem
class Price extends React.Component {
componentWillUpdate(nextProps) {
this.setStateDo not use setState in componentWillUpdate({ total: nextProps.amount * nextProps.quantity });
}
render() {
return <span>{this.state.total}</span>;
}
}example.jsxNo problems
class Price extends React.Component {
render() {
const total = this.props.amount * this.props.quantity;
return <span>{total}</span>;
}
}Options#
| Option | What it does |
|---|---|
| none (default) | Allow this.setState in a function nested in the method, such as a callback that runs later. |
"disallow-in-func" | Report those calls too. |
By default this is allowed, because the callback runs after the update:
example.jsxNo problems
class Price extends React.Component {
componentWillUpdate() {
loadRates().then(rates => {
this.setState({ rates });
});
}
}With "disallow-in-func" it's reported:
example.jsxwith
"disallow-in-func"1 problemclass Price extends React.Component {
componentWillUpdate() {
loadRates().then(rates => {
this.setStateDo not use setState in componentWillUpdate({ rates });
});
}
}