Document the use of setState in componentWillUnmount
See original GitHub issueDo you want to request a feature or report a bug?
Feature
What is the current behavior?
Excerpt from documentation:
componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().
https://reactjs.org/docs/react-component.html
The docs don’t mention if setState
can be used in componentWillUnmount
.
Consider the following example where the state.showGreeting
is undone by timer over time. But since the timer has to be invalidated in componentWillUnmount
there no other place to reset the state:
class HelloWorld extends Component {
state = {
showGreeting: false
};
onClick() {
this.setState({ showGreeting: true })
this._timer = setTimeout(() => this.setState({ showGreeting: false }), 3000)
}
componentWillUnmount() {
clearTimeout(this._timer)
// is it legal?
this.setState({ showGreeting: false })
}
}
Is it legal to call setState
from componentWillUnmount
? Given that it can be asynchronous it feels that setState
may not be invoked until after component is actually unmounted which may produce a warning in my understanding, until… componentWillUnmount
actually pumps up the state’s dispatch queue manually to ensure that all state changes land in component before it’s too late.
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn’t have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:
What is the expected behavior?
Not sure
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
16.2 / Webkit
Issue Analytics
- State:
- Created 6 years ago
- Reactions:6
- Comments:11 (4 by maintainers)
No, it’s not supported or useful. (Happy to take a PR documenting that)
I’m not sure what you’re trying to achieve. If the component is being unmounted, there’s no need to “reset” the state. A component can’t be “resurrected” so if it gets unmounted, its state is irrelevant to the rest of the program.
Maybe we could add a notice in
componentWillUnmount
doc that once a component is unmounted, it can never be re-mounted.