React: Add Event Listeners – Need help understanding it better!

I have several questions about this challenge. I passed it already, but I don’t quite understand it fully.

  1. Why do we need to ‘clean up’ the component?

  2. What does it mean when the component are unmounted and destroyed?

  3. In this challenge, componentWillUnmount() is used to remove the event listener, why do we need to remove it?

  4. Even though I implemented componentWillUnmount(), when I press the enter key, it still renders. And on top of that, multiple h1s are rendered. Why is that happening? I had assumed it would just be a single h1 with the state’s message property in it.

  1. When a component is created it’s using a memory in your system, in this case your browser. Since it’s taking up resources of a browser, if it’s no longer being used, it’s better to clean up the component and free the resources.

  2. It basically means “clean up”.

  3. Same reason as #1.

  4. Can you share your code instead of screenshot so I can see what’s happening?

Could you give me a real-life example of when you only use a code one time and then delete/clean it? Below is the code.

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() {

  }
  componentWillUnmount() {

  }
  // change code above this line
  handleEnter() {
    this.setState({
      message: this.state.message + 'You pressed the enter key! '
    });
  }
  handleKeyPress(event) {
    if (event.keyCode === 13) {
      this.handleEnter();
    }
  }
  render() {
    return (
      <div>
        <h1>{this.state.message}</h1>
      </div>
    );
  }
};

The reason why you have previous messages left there is because your setState is this.setState({ message: this.state.message + 'You pressed the enter key! '

If you remove the this.state.message and only setState as message: 'You pressed the enter key! ' then you will only have one message.

2 Likes

Could you please explain why this solution fixes the problem?

Is because the “this.state.message” is carrying over the previous value?