Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is adding and removing event listeners anti-pattern in React?

Consider this snippet,

useEffect(() => {
        document.addEventListener('mousedown', checkAndCloseMenu);
        return () => document.removeEventListener('mousedown', checkAndCloseMenu);
 }, []);

I am using this useEffect in an Higher Order Dropdown Component, I’ve seen very few professionals using these kinds of adding and remove Event Listeners. Is using these eventListeners anti-pattern ? If yes, what would be the correct approach.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Adding and removing event listeners is not considered an anti-pattern.

useEffect(() => {
  document.addEventListener('mousedown', checkAndCloseMenu);
  return () => document.removeEventListener('mousedown', checkAndCloseMenu);
 }, []);

Whenever/wherever possible it is preferred to use a React ref to access underlying DOMNodes:

const ref = React.useRef();

useEffect(() => {
  const node = ref.current;

  node.addEventListener('mousedown', checkAndCloseMenu);
  return () => node.removeEventListener('mousedown', checkAndCloseMenu);
 }, []);

 ...

 <div ref={ref}> ..... </div>

or to attach the listeners directly

<div onMouseDown={checkAndCloseMenu}> ..... </div>

but sometimes this is unavoidable when you need to listen to event from the window and document objects/nodes.

What is considered anti-pattern is directly mutating a global event listener.

document.onmousedown = checkAndCloseMenu;

Not only does doing so mutate a global object it will replace any existing values there. Don’t do event handling like this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading