Ad

React: Unmount Event Listener From Server

- 1 answer

In my app.js I am mounting event listeners. After several reloads I am getting "warning: possible EventEmitter memory leak detected. 11 change listeners added".

My code is like so.

  let App = React.createClass({

     componentWillMount() {
       ArticleStore.addChangeListener((e) => this.onArticleChange(e));
     },

     componentWillUnmount() {
       ArticleStore.removeChangeListener(e);
     }

   }

However, componentWillUnmount never gets called in app.js because it exists on the server and I end up with a lot of event listeners open causing the above error and maxing out my event listener limit.

How can I unmount any event listeners in my app.js?

Ad

Answer

componentWillMount is called on the server, but componentDidMount is not. To prevent leaks, you'll generally want to use componentDidMount for event registration.

let App = React.createClass({

   componentDidMount() {
     ArticleStore.addChangeListener((e) => this.onArticleChange(e));
   },

   componentWillUnmount() {
     ArticleStore.removeChangeListener(e);
   }

 }
Ad
source: stackoverflow.com
Ad