The code below according to the link react says that:
Unfortunately, this can cause memory leaks for server rendering (where componentWillUnmount will never be called)
// Before
class ExampleComponent extends React.Component {
componentWillMount() {
this.setState({
subscribedValue: this.props.dataSource.value,
});
// This is not safe; it can leak!
this.props.dataSource.subscribe(
this.handleSubscriptionChange
);
}
componentWillUnmount() {
this.props.dataSource.unsubscribe(
this.handleSubscriptionChange
);
}
handleSubscriptionChange = dataSource => {
this.setState({
subscribedValue: dataSource.value,
});
};
}
I cant understand how this can be a memory leak in server-side. For example, lets say we have this code which is rendered server-side and the ExampleComponent contains the memory leak.
import React from 'react';
import ReactDomServer from 'react-dom/server';
import App from './components/index'
const serverRender = () =>{
return ReactDomServer.renderToString(<ExampleComponent />);
};
export default serverRender;
When this returns to the client, the rendered components are not attached to anywhere and are ready to be GB collected. So why is there a memory leak?
this.props.dataSource
is something external and can live longer than the component calling subscribe
. handleSubscriptionChange
will be referenced by this.props.dataSource
. Also the component itself might be referenced by this
inside handleSubscriptionChange
. So GB won't clean up ExampleComponent
at all.
Since componentWillMount is deprecated you probably should not worry about these details and just use componentDidMaount
.