Ad

Exact Place To Bind And Remove Events In React

- 1 answer

I have added an eventListener in componentWillMount and removed it in componentWillUnMount.

Like this

componentWillMount() {
    store.on("onSuccess", this.onSuccess);
}

componentWillUnMount() {
    store.removeListener("onSuccess", this.onSuccess);
}

But Component gets loaded in DOM on button click. Actually there is a flag for this component. Each time I click a button, flag sets true and componentWillMount gets called. but when flag is set false, componentWillUnmount is not getting called even when component is not present in DOM.

So what happens is, when again I click on button component appears, but I emit an event, the listener is getting triggered twice. I am thinking that is because older component is still present and still listens the event.

So I just want to know, what is the exact place to removeListeners.

Ad

Answer

It seems that you just have a misprint in componentWillUnMount() lifecycle method. It should be componentWillUnmount() instead (with lower m).

Additional info:

In newer versions of ReactcomponentWillMount lifecycle method became legacy (and renamed to UNSAFE_componentWillMount()) and will be removed in React 17. It's recommended to use componentDidMount() lifecycle method for such purposes instead. (see more detailed information about legacy lifecycle methods.

Ad
source: stackoverflow.com
Ad