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".

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])

Leave a Reply