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

Why EventListener is not removing?

I ´ve made my own modal which has a function to listen when a click happens outside of itself. The problem is that the eventListener is not removing, probably because I may be using useEffect in a wrong way.

This is my custom Hook "useModal":

import { useEffect, useState } from "react";

export const useModal = ( ref ) => {
    const [modal, setModal] = useState('none')

    const onClick = () => {
      modal === 'none' ? setModal('flex') : setModal('none')
    }
  
    useEffect(() => {
      const checkIfClickedOutside = (e) => {
        console.log('hola');
        if( modal === 'flex' && ref.current && !ref.current.contains(e.target) ){
          onClick();
        }
      };
      document.addEventListener("click", checkIfClickedOutside); 
      return () => {
        document.removeEventListener("click", checkIfClickedOutside);
      }
    }, [modal])

    return{
        onClick,
        modal
    }
}

I need to remove the eventListener when modal is "none".

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

I have tried changing dependencies but anyone works.

>Solution :

you have dependency modal, everytime modal value changes it will be re-rendered whatever the value is removing one listener and again setting one addListener when you have modal===’none’

try this

 useEffect(() => {
  const checkIfClickedOutside = (e) => {
    console.log('hola');
    if( modal === 'flex' && ref.current && !ref.current.contains(e.target) ){
      onClick();
    }
  };
  modal !==none && document.addEventListener("click", checkIfClickedOutside); 
  return () => {
    document.removeEventListener("click", checkIfClickedOutside);
  }
}, [modal])
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