DEV Community

Discussion on: React Component to Smooth Scroll to the Top

Collapse
 
link2twenty profile image
Andrew Bone

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";

export default function ScrollToTop() {
  const [isVisible, setIsVisible] = useState(false);

  // Top: 0 takes us all the way back to the top of the page
  // Behavior: smooth keeps it smooth!
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth"
    });
  };

  useEffect(() => {
    // Button is displayed after scrolling for 500 pixels
    const toggleVisibility = () => {
      if (window.pageYOffset > 500) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    window.addEventListener("scroll", toggleVisibility);

    return () => window.removeEventListener("scroll", toggleVisibility);
  }, []);

  return (
    <div className="scroll-to-top">
      {isVisible && (
        <div onClick={scrollToTop}>
          <h3>Go up!</h3>
        </div>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

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 😉

Collapse
 
prnvbirajdar profile image
Pranav Birajdar

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!