Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a state update on an unmounted component cause a memory leak?

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?

like image 433
Jordan Avatar asked Dec 31 '22 11:12

Jordan


1 Answers

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.

like image 122
Nicholas Tower Avatar answered Jan 13 '23 15:01

Nicholas Tower