Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I clear state in componentWillUnmount?

Tags:

react-native

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.

like image 836
Sung Jin O Avatar asked Jun 21 '16 05:06

Sung Jin O


People also ask

What is the best way to manage state in React?

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.

Can you set state in componentWillUnmount?

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.

What is the best method to update state in component?

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.

How do you clear the state in React?

To reset a component to its initial state: When an event occurs, call the setState() function, passing it the initial state.


1 Answers

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.

like image 124
Alejandro B. Avatar answered Oct 29 '22 12:10

Alejandro B.