Why attach event listeners to componentDidMount()?

I tried to research why event listeners are best attached to the componentDidMount() method but couldn’t find an explanation. Anyone able to explain this? Thanks…

Event listeners can only be attached to elements actually in the DOM. componentDidMount() is the point in the react component’s lifecycle when you can guarantee that the DOM element has been created and mounted.

It’s common, with newer developers, to attach an event listener at the page load, say listening for a click on all elements with the class “clickable-foo”, and then wonder why elements being added dynamically later aren’t using our listener. This is the react way of avoiding that pitfall - by adding listeners at the componentDidMount(), then we know that it is in the DOM, so we can listen.

Further, it’s not a bad practice to remove your listeners in the componentWillUnmount() lifecycle point. This is the place to stage any changes to that DOM node, just prior to its being removed from the DOM. Just in case. :wink:

2 Likes