Questions about Drum Machine code

Hi campers,

I have 2 questions regarding the drum machine code that freeCodeCamp provided. The project code is here.

1. Why do we need to put this code in a block?

In “App” component line 296-301, the code is inside a curly bracket block. I removed it and nothing seems to be affected.

    {
      const clips = [].slice.call(document.getElementsByClassName('clip'));
      clips.forEach(sound => {
        sound.volume = this.state.sliderVal
      });
    }

2. Why do we need “componentWillUnmount” function?

In “DrumPad” component line126 - 128 we have a “componentWillUnmount” function, I’ve tried to remove it and again, nothing seems to be affected.

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyPress);
  }

which brings me another minor question: Is this how we add an event listener in React?

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyPress);
  }

by that I mean, put it in a function and it will be call automatically?

Thanks!

We don’t. It’ll work the same with or without curly braces. I’d personally prefer to keep braces because it makes code more readable.

It’s a “best practice” to clean up after yourself - when you create event listeners, timers etc. you should remove them when you unmount the component or you may encounter memory leaks.

Nothing React specific here - this is how you’d add a global event listener in a regular javascript.

1 Like

Thanks for the clear explanation @jenovs !

componentWillUnmount is a life cycle method (life of the react Component). Is called only on certain circumstances.
When is called in your case is executing the method .removeEventListener of the document object.

When an HTML document is loaded into a web browser, it becomes a document object .

The document object is the root node of the HTML document.

I believe that any web developer should have a good understanding of the DOM https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction

1 Like

Is called only on certain circumstances.

Can you elaborate more, please?

From React documentation:

This method is called when a component is being removed from the DOM:

componentWillUnmount()

So when it is called, is executing your removeEventListener code.

More at https://reactjs.org/docs/react-component.html

1 Like

Thanks for the pointer!