Search code examples
javascriptreactjsnext.jsurl-routing

Next.js 13 maintains scroll position when routing to next page


I have a problem regarding Next.js 13 routing. When I want to go from one page to another and the new page is fetching data, Next.js 13 maintains the scroll position of the previous page. But if there is not data fetching in the beginning, the scroll position of the new page is at the top, just like it should be. I dont know why this is the case and I also dont know how I could fix this. Maybe some of you had the same issue.

You can test this behaviour on my website. Be aware that to this point I only designed it for mobile phones so it looks awful on desktop but it should help you to get what I mean: https://csgo-kapsel.vercel.app/

Here are some parts of my Code:

Component used to go to the next page:

"use client"

import { useRouter } from "next/navigation";

function CapsuleCard({ title, icon, stickerValue, capsulePrice, hoverAnimation, detailPage }: Props) {
    const router = useRouter();

    return (
        <div className={styles.card} onClick={() => { detailPage ? router.push(detailPage) : null }}>
             //other code
        </div>
    )
}

export default CapsuleCard;

The next page:

type Props = {
  params: {
    id: string
  }
}

async function Page({ params: { id } }: Props) {
  //Scroll position maintains because of this fetch
  const capsuleData = await getCapsule(id);

  return (
    <>
      //some code
    </>
  )
}

export default Page

Also I found this issue which sounds related to mine, I tried everything from the comments but the issue still persists.

I hope you can help me with that.

Thanks in advance.

Orchi


Solution

  • I resolved this issue by removing the "async" keyword and therefore converting this function into a react functional component. With that I was able to use the useEffect hook and make my request there. By doing so, the scroll position is not maintained anymore.

    Here is my updated code (the component used to go to the next page stayed the same):

    "use client"
    
    type Props = {
      params: {
        id: string
      }
    }
    
    function Page({ params: { id } }: Props) {
      const [capsuleData, setCapsuleData] = useState<CapsuleData>();
      const [fetchError, setFetchError] = useState<string>();
    
      useEffect(() => {
        const getCapsuleData = async () => {
          try {
            const capsuleData = await getCapsule(id);
            setCapsuleData(capsuleData);
          } catch (error: any) {
            setFetchError(error.message);
          }
        }
    
        getCapsuleData();
      }, []);
    
      return (
        <>
          //some code
        </>
      )
    }
    
    export default Page