This is pretty cool and a great way to get people up and running fast there's one minor change I'd make though.
import{useEffect,useState}from"react";exportdefaultfunctionScrollToTop(){const[isVisible,setIsVisible]=useState(false);// Top: 0 takes us all the way back to the top of the page// Behavior: smooth keeps it smooth!constscrollToTop=()=>{window.scrollTo({top:0,behavior:"smooth"});};useEffect(()=>{// Button is displayed after scrolling for 500 pixelsconsttoggleVisibility=()=>{if(window.pageYOffset>500){setIsVisible(true);}else{setIsVisible(false);}};window.addEventListener("scroll",toggleVisibility);return()=>window.removeEventListener("scroll",toggleVisibility);},[]);return(<divclassName="scroll-to-top">{isVisible&&(<divonClick={scrollToTop}><h3>Go up!</h3></div>)}</div>);}
By moving the function into the useEffect it is only declared once rather than on every draw. Also by adding a return to that same useEffect we can stop listening if the component is ever unmounted.
As an interesting side point you could look into using IntersectionObserver, with a scroll event fallback, if you wanted to improve on performance, but I don't think this would really need it 😉
Thank you for pointing out the cleanup for useEffect. I always tend to forget that. I had not considered IntersectionObserver since I didn't know there was a performance hit, but I will certainly look into it!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
This is pretty cool and a great way to get people up and running fast there's one minor change I'd make though.
By moving the function into the
useEffect
it is only declared once rather than on every draw. Also by adding a return to that sameuseEffect
we can stop listening if the component is ever unmounted.As an interesting side point you could look into using
IntersectionObserver
, with a scroll event fallback, if you wanted to improve on performance, but I don't think this would really need it 😉Thank you for pointing out the cleanup for useEffect. I always tend to forget that. I had not considered
IntersectionObserver
since I didn't know there was a performance hit, but I will certainly look into it!