Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
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.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda