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

How the returned function is not destroying event listener in useEffect?

I made this custom hook to get window width. It is working but I have a question.
I used useEffect to add event listener to window at component mount. But then my friend suggested me to use return function to remove the event listener.
How this is working? Shouldn’t the returned function destroy the event listener and make it not work? Since this is happing one time on component mount ?

import React from "react";

const useWindowSize = () => {
  const [windowSize, setWindowSize] = React.useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
  const windowResize = () => {
    setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight,
    });
  };
  React.useEffect(() => {
    window.addEventListener("resize", windowResize);
    return () => {
      window.removeEventListener("resize", windowResize);
    };
  }, []);
  return windowSize;
};

export default useWindowSize;

>Solution :

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

shouldn’t return function destroy event listener and make it not
work? since this is happing one time on component mount ?

Well the return function will be executed in your case when the component using the hook unmounts (because of empty array as dependencies), so at that time, it makes sense to unregister the listener. Isn’t it? More reading.

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