DEV Community

Discussion on: How to create a Scroll to Top Button with React

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Really nice post :)

One thing - your useEffect(()=>window.addListener(... is being called on every re-render so you will end up with lots of them added. You should return a function to remove the listener so it tidies up and possibly rewrite things a bit so you can actually only do it on mount/unmount with deps of []. Care needs to be taken with that though because the you need to be sure that the handler can work in cases when it wasn't added on the same render (it's a closure on the time the deps change).

Collapse
 
silviaespanagil profile image
Silvia España Gil

Thank you very much Mike, I'll put at eye on it and see if I find a solution so it works in every scenario!

Collapse
 
hassankhademi profile image
hassanKhademi

useEffect(() => {
window.addEventListener("scroll", handleVisibleButton);
},[]);
For fix issue this way is great
execute when component mounting
One listener

Collapse
 
hashcode01 profile image
Hash

what about removing the listener when unmouning,


useEffect(() => {
const e = window.addEventListener("scroll", handleVisibleButton);

return ()=> window.removeEventListener('scroll',handleVisibleButton);
},[]);

Enter fullscreen mode Exit fullscreen mode