reactjsreact-hooks

Trigger useEffect on second pathname change


I want to scroll down below the hero block when a user changes the page. I have this code so far in my App.jsx:

const { pathname } = useLocation()
 const paragraphRef = useRef(null)
 useEffect(() => {
    window.scroll({
      top: paragraphRef.current.offsetTop,
      behavior: "smooth",
      block: "start"
    })
  }, [pathname])

The problem is that I want the Hero block visible on the first visit and trigger the scrolldown afterwards on every page.


Solution

  • You can use a state variable to track whether the user has visited the page before:

      const { pathname } = useLocation();
      const paragraphRef = useRef(null);
      const [hasVisited, setHasVisited] = useState(false);
    
      useEffect(() => {
        if (hasVisited && paragraphRef.current) {
          window.scroll({
            top: paragraphRef.current.offsetTop,
            behavior: "smooth",
            block: "start",
          });
        } else {
          setHasVisited(true);
        }
      }, [pathname, hasVisited]);
    

    Explanation: State Variable (hasVisited): Tracks whether the user has visited the page before. Initially, it is false, which prevents the scroll action on the first visit.