Reputation: 4813
How does updating the state of an unmounted component cause a memory leak?
It is known how to fix the following error (one solution, another solution)
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
But it seems odd to litter my promise chains with "isUnmounted" checks when the component has just been dismissed and is not needed anymore. How does this cause a memory leak?
Upvotes: 5
Views: 627
Reputation: 138267
How does updating the state of an unmounted component cause a memory leak?
It does not.
it indicates a memory leak in your application.
In most cases, you just do the asynchronous action to update the components state, so if the component unmounted, there is no sense in doing the asynchronous task at all. In other words: You are wasting ressources for no effect after all. That's a memory leak.
Here is an example:
setInterval(() => { // If the component unmounted, this is a waste of ressources
component.setState(({ count }) => ({ count: count + 1 }));
}, 10);
Upvotes: 3
Reputation: 85002
How does this cause a memory leak?
It's not guaranteed to, but it might depending on what's causing you to set state after unmount. For example, if you have a setInterval
that's continuing to run after unmount, that function and any variables in its closure cannot be garbage collected.
class ExampleComponent extends React.Component {
state: { seconds: 0 }
componentDidMount() {
setInterval(() => {
this.setState(prev => ({
seconds: prev.seconds + 1;
});
}, 1000);
}
// No clearing the interval in componentWillUnmount
}
In the above code, the anonymous function inside set interval cannot be garbage collected, which in turn means this
cannot be collected, so the component will have to hang out in memory forever.
Upvotes: 8