Johnxr
Johnxr

Reputation: 316

Difference in UseEffect and event listeners with React?

So I'm trying to understand what's wrong with writing this event listener in React? I notice others wrap it in a useEffect hook and add a removeEventlistener, but I don't understand the point because it does the same thing as my code.

Here's my code

function App() {

 const hideMenu = () => {
   if (window.innerWidth > 768) {
   setIsOpen(false);
  }
 };

 window.addEventListener('resize', hideMenu);

}

What's the point of putting this code into a useEffect hook? Why can't I just use my code above and be fine?

Here's the same code put inside of a useEffect hook

      useEffect(() => {
        const hideMenu = () => {
          if (window.innerWidth > 768) {
            setIsOpen(false);
          }
        };

        window.addEventListener('resize', hideMenu);
      }, []);

Based off my site, both methods do the exact same thing, so how do I check in my console the purpose of doing useEffect vs the way I wrote it?

The whole point of my function is just to hide the mobile menu if the screen is larger than 768px.

Upvotes: 2

Views: 1894

Answers (1)

PurpSchurp
PurpSchurp

Reputation: 646

There are 2 problems you can run into with your solution.

  1. Every time a state variable changes or the component is re-rendered, it adds a new event listener to your window. If it is in a use effect with empty brackets, it will only run the first time the component is rendered, similar to a "ComponentDidMount".

  2. If this were not your very top root component, and someone were to switch away from your screen, currently you aren't removing your event listener. This could be problematic in the future, or just be listening for useless information. When you remove the listener when it dismounts, it guarantees it is gone when it is unused, and if you were to go back, it would re-add the listener.

      useEffect(() => {
        const hideMenu = () => {
          if (window.innerWidth > 768) {
            setIsOpen(false);
          }
        };

        window.addEventListener('resize', hideMenu);

        return () => {
          window.removeEventListener('resize', hideMenu);
        }
      }, []);

Upvotes: 3

Related Questions