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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…