useWindowScroll.removeEventListener()
Dobby89 opened this issue · 2 comments
Could you provide a method to clean up/destroy the event listener for useWindowScroll
?
After I've used it, I no longer want the event listener to run and I should be able to clean up.
For example:
function MyComponent() {
const { scrollY, cleanUp } = useWindowScroll();
const [showMessage, setShowMessage] = useState(false);
useEffect(() => {
if (scrollY > 300) {
setShowMessage(true);
cleanUp();
}
}, [scrollY]);
return (
<div>{showMessage ? "You've scrolled far enough!" : 'Keep scrolling'}</div>
);
}
That's kind of out of the scope of the hook as it already cleans up after itself:
https://github.com/jaredLunde/react-hook/blob/master/packages/window-scroll/src/index.js#L23
Something you could do is once your threshold is reached change the fps
argument to 0
. This way the listener will still exist but the state of the hook won't be updated anymore and your component will stop re-rendering each change of scroll position.
e.g.
function myComponent() {
const [fps, setFps] = useState(30)
const scrollY = useWindowScroll(fps);
const [showMessage, setShowMessage] = useState(false);
useEffect(() => {
if (scrollY > 300) {
setShowMessage(true);
setFps(0);
}
}, [scrollY]);
return (
<div>{showMessage ? "You've scrolled far enough!" : 'Keep scrolling'}</div>
);
}
In the example I've given the hook will only clean itself up if MyComponent
is unmounted, which arguably wouldn't happen if it was the root app component. So in this instance it would be useful to be able to manually clean up the event listener.
I don't agree this is out of scope. Would you accept a pull request?