Home > Software design >  How to remove/cleanup EventListener when handler is outside useEffect hook?
How to remove/cleanup EventListener when handler is outside useEffect hook?

Time:11-15

I am wondering if I could cleanup the Event Listener if its handler declared outside the useEffect hook, I saw many examples and tutorials removing Event Listeners this way, by implementing the handler function inside the useEffect hook:

 useEffect(() => {
    
    function updateSize(){
      setSize([window.innerWidth, window.innerHeight]);
    };

    window.addEventListener("resize", updateSize);
    updateSize();

    return () => window.removeEventListener("resize", updateSize);
  }, []);

While I did implement the handler out side the useEffect hook, the listener is working fine, but not sure if it a correct way and would be able to get cleaned by useEffect hook since it is outside the scope.

const Component = () => {
  const [size, setSize] = useState([0, 0]);

   const updateSize = () => {
     setSize([window.innerWidth, window.innerHeight]);
  };


  useEffect(() => {

    window.addEventListener("resize", updateSize);

    updateSize();
    return () => window.remove
  }, []);



  return (
    <>
    </>
  )
}

CodePudding user response:

How to remove/cleanup EventListener when handler is outside useEffect hook?

Even if the handler (in your case - updateSize) is declared outside the useEffect hook, you still have the reference to it. Does not really matter if it's declared outside the hook.

Just remove it (clean up) as you would do with a normal listener.

useEffect(() => {
   window.addEventListener("resize", updateSize);

   return () => {
      window.removeEventListener("resize", updateSize);
   };
}, []);

Note: Remember to put it inside the dependency array of useEffect and wrap the updateSize with useCallback hook.

  • Related