Reputation: 45
My component has a button. By clicking the button, an action is dispatched and a corresponding API call is made. The response from the API call is stored in redux. But whenever there is an update to the redux store, the component (that I was working on) gets unmounted and remounted. So the component's internal state is destroyed and recreated when the component is remounted.
My question is:
Is it expected for components to unmount and remount whenever the redux store is updated? If it is expected, how should I persist the component's internal state?
AsyncComponent:
export default function asyncComponent(importComponent) {
class AsyncComponent extends React.Component {
state = {
component: null
};
isComponentMounted = false;
componentWillMount() {
this.isComponentMounted = true;
}
async componentDidMount() {
const { default: component } = await importComponent();
if (this.isComponentMounted) {
this.setState({ component });
}
}
componentWillUnmount() {
this.isComponentMounted = false;
}
render() {
// eslint-disable-next-line react/destructuring-assignment
const C = this.state.component;
return C ? <C {...this.props} /> : <Loader />;
}
}
return AsyncComponent;
}
Upvotes: 3
Views: 2726
Reputation: 2452
It totally depends on your implementation and not on Redux state.
If you have a condition to render the component then when the condition is false the component may get destroyed. If you're passing state as a prop then it may just update without unmounting.
In your case it seems like you're using state as a condition to render the component.
Upvotes: 2
Reputation: 88
On redux store update the component will not re-mount, it will re-render.It may happen that the parent component is getting re-render and your current component is getting data through props from parent, hence you are observing the issue.Please check the parent component once.
Upvotes: 0