Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Server side + Nodejs setInterval memory leaks

In my universal react application, I'm having a react component containing setInterval in componentWillMount and clearInterval in componentWillUnmount.

Fortunately, componentWillUnmount not called on the server.

componentWillMount(){
    this.checker = setInterval(this.checkForSubscription, 2000);
}

componentWillUnmount(){
    clearInterval(this.checker);
}

I'm suffering from crashes and memory leaks on my express server. I created heapdumps and analysis those on chrome memory tool.

Unfortunately, got no success to find memory leaks. So, when I remove the setInterval from server side logic by checking typeof for window object. I do not create any crash since then. So, I want to know the code above is the cause of memory leaks and why?

like image 308
Anurag Jain Avatar asked Mar 13 '26 20:03

Anurag Jain


1 Answers

You can safely migrate you method to componenDidMount which is not called on server

componentDidlMount(){
    this.checker = setInterval(this.checkForSubscription, 2000);
}

componentWillUnmount(){
    clearInterval(this.checker);
}

what you can also do is using more packages like can-use-dom

import canUseDOM from 'can-use-dom';
componentWillMount(){
    canUseDOM && this.checker = setInterval(this.checkForSubscription, 2000);
}

componentWillUnmount(){
    clearInterval(this.checker);
}

If you are using webpack you can just define an env variable in config

   new webpack.DefinePlugin({
      'process.env': {
        BROWSER: JSON.stringify(true),
      },
    }),

and use condition process.env.BROWSER && "your code"

like image 178
Denis Rybalka Avatar answered Mar 16 '26 09:03

Denis Rybalka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!