Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda