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

by
Alexei Petrov
next.js reactjs url-routing

Quick Fix: The problem can be resolved by removing the "async" keyword from the function that was making the request. This can be useful when you don’t need data from the request immediately and you want to maintain the scroll position.

The Problem:

In Next.js 13, when routing from one page to another, if data fetching is involved on the new page, the scroll position of the previous page is maintained. However, if there’s no data fetching initially, the scroll position of the new page is reset to the top, causing an inconsistent behavior. This behavior is observed on a website designed for mobile phones: https://csgo-kapsel.vercel.app/. The cause and solution for this issue need to be determined.

The Solutions:

Solution 1: Convert the function to a react functional component and use useEffect hook

The issue was caused by the use of the async keyword which converted the function into an async function. This made it impossible to use the useEffect hook. To resolve this, the function was converted into a react functional component, and the useEffect hook was used to make the data request.

  1. Remove the async keyword from the function declaration.

  2. Use the useState hook to manage the state of the page. In this case, we are using it to store the fetched capsule data and an error message.

  3. Use the useEffect hook to make the data request. The useEffect hook will run the provided function after the component is mounted.

  4. Inside the useEffect hook, define an async function to make the data request.

  5. Use the try/catch block to handle any errors that may occur during the data request.

  6. Update the state with the fetched data or the error message if there is an error.

Q&A

Why does Next.js 13 maintain scroll position on routing?

Fetching data on page load maintains scroll position, while fetching in a React functional component does not.

How to fix scroll position maintenance on routing in Next.js 13?

Move data fetching to a React functional component and use the useEffect hook to make the request.

Video Explanation:

The following video, titled "Next.js Pages, Layout, Links, Routes & Loading | Next.js 13 tutorial ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Web Dev Roadmap for Beginners (Free!): https://bit.ly/DaveGrayWebDevRoadmap Learn about Next.js pages, layout, links, routes, loading, ...