Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upCalling setState in componentDidUpdate #1875
Comments
|
|
|
The new lifecycle method |
|
It would be reasonable, in React 16 and later, to modify the rule's behavior so that it does not warn on "safe" usages of setState. |
|
(this would need to be done in eslint-plugin-react, however, not here) |
@dlwalsh, you may want to check this technique from the official React blog but I would suggest to read the entire article -- maybe you can completely avoid usage of |
|
Polluting |
|
@dlwalsh yep it sucks, but it's inevitable in some cases. How do you change the state of a component reacting from a change from react-router that pass match through props? |
|
componentDidUpdate is the appropriate place to put asynchronous server updates so this warning is patently false, misleading and confusing. |
|
This rule should be removed or modified to check for a condition. The React docs themselves explain how to safely update the state within componentDidUpdate:
|
|
FWIW, I like to outsource lifecycle method work to (other) named methods in order to ensure they remain segmented by concern. This rule only looks for componentDidUpdate(lastProps: Props) {
this.updateCursorSuggestionIfNeeded(lastProps.data)
}
updateCursorSuggestionIfNeeded(lastData: WhateverData) {
const { data } = this.props
if (needsUpdate(data, lastData)) {
// no way for linter to warn here, with or without the above condition
this.setState(updatedStateForData(data))
}
}Keeps things neat and negates the (in this case, unnecessary) lint warning. |


It might be worth revisiting react/no-did-update-set-state.
Now that
componentWillReceiveProps()is being deprecated,componentDidUpdate()is the only "safe" way to detect changes in props and set state accordingly.The React docs say calling
setState()incomponentDidUpdate()is permitted, albeit with caveats.