3

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?

2 Answers 2

1

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"

Sign up to request clarification or add additional context in comments.

2 Comments

I can handle this with ease by checking the existence of the window object. My question is, will it create a memory leak on node server since componentWillUnmount is not called on the server?
No, all 3 examples will not create any memory leaks
0

I found it my own. The problem with above code is that it cannot call clearInterval on the server side since componentWillUnmount has not called on the server. So, it causes a memory leak on server.

Once I set the check for the existence of window object, it only called on the client side. So, no server crash since then.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.