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.
-
Remove the async keyword from the function declaration.
-
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. -
Use the
useEffect
hook to make the data request. The useEffect hook will run the provided function after the component is mounted. -
Inside the useEffect hook, define an async function to make the data request.
-
Use the
try/catch
block to handle any errors that may occur during the data request. -
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.
Web Dev Roadmap for Beginners (Free!): https://bit.ly/DaveGrayWebDevRoadmap Learn about Next.js pages, layout, links, routes, loading, ...
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.
Web Dev Roadmap for Beginners (Free!): https://bit.ly/DaveGrayWebDevRoadmap Learn about Next.js pages, layout, links, routes, loading, ...