React hooks, addEventListener only when element is visible

When im to add an event listener with react hooks i do the standard useEffect approach:

  const handleClick=()=>{
    console.log('click event')
  window.addEventListener('click', handleClick)
  return ()=>window.removeEventListener('click', handleClick)
}, [])

But what if i want to add the event listener only when certain criteria is true, lets say an element is visible(does not have display set to none), or the size of the window is large(window.innerWidth>1000). I cant put hooks conditonally. Where the condition should be put? Before and after the add&remove listener methods?

if (windowIsBig) window.addEventListener('click', handleClick)
if (!windowIsBig) return ()=>window.removeEventListener('click', handleClick)

In this case, i suppose ill have to add windowIsBig in the dependency array, but under what hood i should place this variable. How to update the condition, so the useEffect register the change? A state value, a ref value, or simply aregular variable?

I think we need the actual context for what you are trying to do.

Conditionally attaching the listener seems a bit over-complicated if it’s just for a conditionally rendered element and you normally wouldn’t attach the click listener to the window/document but to the element.

I have a button element, which is only visible when the screen is bellow 300px(designed for mobile view). This button is meant to hide/show the navbar menu of the website(for screens wider than 300px, the navbar is always visible, while the toggle button is set to display: none). I want to design event handlers, which are associated with the toggle button functionality and should only be operating, while the button is not with display: none(its visible on the screen). The button itself has a click handler, but i need event listener attached to the window and track “resize”. The window “click” event is another matter, as it should tell when the user clicks anywhere outside the button, in which case, the nav menu should close, but obviously that event should be monitored only when there is actually a toggle button.
The main issue i have is actually make the event listeners be there only when they are needed. I dont need an event that tells me if the user has clicked outside the button, while there is not even such button, nore trigger some functionality produced of that click.
Im sorry i dont provide a code snippet, but my project is laid out in VS Code, React App and there are mutltiple files involved, for components, handlers, styles and whatnot. Im just hoping someone has faced the particular problem of attaching and removing handlers conditionally with react hooks and if there is a good practice for that.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.