yigal
yigal

Reputation: 4715

Preserve react component state on unmount

React newbie here: I have noticed that the component state gets cleared on unmount. is there a way to prevent it? is it using redux?

Upvotes: 0

Views: 3755

Answers (2)

Menelaos Kotsollaris
Menelaos Kotsollaris

Reputation: 5506

You have a plethora of options. You can either use a state management tool, like redux, context API and so on, or you can pass-in a callback to your parent component and trigger it on childComponentWillUnmount like this:

ParentComponent.jsx:

childComponentWillUnmount = (data) => {
 console.log('my data', data);
}

render(){
  return <div>
    <Child componentUnmountCallback={this.childComponentWillUnmount()}/>
  <div>
}
<div>

Child.jsx

...

componentWillUnmount() {
   this.props.childComponentWillUnmount(this.state);

}

...

Upvotes: 1

Nico Diz
Nico Diz

Reputation: 1504

As you say, when a component is unmount you can not access to the state. And thats the way it is because the lifecicle of the component.

What you can do is try to save the state of the component that was instantiated while it is mounted and every time it is updated.

  • You can use the storage and use simple javascript.
  • You can have the state in the parent or another ancester instance.
  • You can have the state in the redux store. Note that your component will receive the vars as props, so it wont be the state properly said.

    You can use redux in order to manage the state and the states values through time. I recommend you the redux-devtools-extension and also this article about it.

Upvotes: 1

Related Questions