I set code like below.
componentWillUnmount() {
this.setState({'modal':false}) or this.setState({})
}
But state is not clear. How can I do this? I need clear state when leave component.
Local state is most often managed in React using the useState hook. For example, local state would be needed to show or hide a modal component or to track values for a form component, such as form submission, when the form is disabled and the values of a form's inputs.
You should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.
setState method allows to change of the state of the component directly using JavaScript object where keys are the name of the state and values are the updated value of that state. Often we update the state of the component based on its previous state.
To reset a component to its initial state: When an event occurs, call the setState() function, passing it the initial state.
According to people at Facebook, setState should not be called on componentWillUnmount as the component is about to be destroyed and never remounted. If you just want to "clear" the state, then there is no need for that, as any new instance of the component will have the clear initial state.
See here any issue where this is talked about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With