I have a scroll event listener and I want to remove it based on page URL, how can I handle it using in a hook component?
useEffect(() => {
function handleScrollEvent() {
if (window.scrollY > 100) {
setHeaderIsVisible(true);
} else {
setHeaderIsVisible(false);
}
}
if (props.location.pathname === "/") {
window.addEventListener("scroll", handleScrollEvent, true);
} else {
window.removeEventListener("scroll", handleScrollEvent, true);
}
}, [props.location.pathname]);
Where I should define the handleScrollEvent to remove it from listener?
TLDR; Always remove event listeners when you don't plan on using them any longer.
We set an event handler to the onClick event of the button, so when the button is clicked, the handler function will be called. In the handler function, we use the setState function for the visibility state to update the state. const removeElement = () => { setVisible((prev) => ! prev); };
What is componentDidUpdate? ComponentDidUpdate is a React component lifecycle method invoked immediately after a component's updates are flushed to the DOM. This is one of the most used built-in methods, which is not called for the initial render nor applicable to your functional details.
What you need to do is every time you add it, you also remove it.
When props.location.pathname
changes, it will remove the event listener.
useEffect(() => {
if (props.location.pathname === "/") {
function handleScrollEvent() {
if (window.scrollY > 100) {
setHeaderIsVisible(true);
} else {
setHeaderIsVisible(false);
}
}
window.addEventListener("scroll", handleScrollEvent, true);
// every time you add it, you also remove it when props.location.pathname changes
return () => {
window.removeEventListener("scroll", handleScrollEvent, true);
}
}
}, [props.location.pathname]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With