Add event Listener question about componentWillUnmount()

Hello Everyone,
so my question is actually what is the difference here IF we do not write the componentWillUnmount() method.
I like to test everything to make sure I know what each thing is being used for but in this case if i press Enter with the componentWillUnmount() method I have the same result as if I had pressed it without the componentWillUnmount() in the code.

Could someone explain to me what it is doing here?


class MyComponent extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    message: ''
  };
  this.handleEnter = this.handleEnter.bind(this);
  this.handleKeyPress = this.handleKeyPress.bind(this);
}
// Change code below this line
componentDidMount() {
document.addEventListener("keydown",this.handleKeyPress)
}
componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeyPress)
}
// Change code above this line
handleEnter() {
  this.setState((state) => ({
    message: state.message + 'You pressed the enter key! '
  }));
}
handleKeyPress(event) {
  if (event.keyCode === 13) {
    this.handleEnter();
  }
}
render() {
  return (
    <div>
      <h1>{this.state.message}</h1>
    </div>
  );
}
};
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36.

Challenge: Add Event Listeners

Link to the challenge:

It’s a best practice to cleanup all the event listeners, timers etc. on unmounting the component to avoid memory leaks.

2 Likes

Yes, it will probably work the same in this context. The point is that you are removing the event listener: if you don’t, then it may (depending on what’s occurring in the app in the browser) not be automatically cleaned up, the listener will stay in place, listening for changes that will never come, which can cause memory leaks. (Edit: exactly what @jenovs says)

2 Likes

Thank you very much :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.