Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

260
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!