Disable Scroll Restoration in Next 13
Nov 26 2023
In next 13, when navigating to a new route, the default behavior is to scroll to the top of the page. However, there are scenarios where you might want to customize this behavior. Here is how to achieve this.
Disabling Scroll Restoration
To disable the scroll restoration behavior, you can use the scroll prop in the <Link>
component or the scroll option in the router.push()
or router.replace()
methods.
Using component
The component is a powerful tool in Next.js for creating navigational links. To disable scroll restoration, simply add the scroll={false} prop to the component:
// next/link
<Link href="/dashboard" scroll={false}>
Dashboard
</Link>
In this example, clicking on the "Dashboard" link and navigating to the "/dashboard" route will no longer trigger a scroll to the top of the page.
Using useRouter
For more programmatic control over navigation, you can utilize the useRouter hook provided by Next 13. Here's an example of using router.push() with the scroll option set to false:
import { useRouter } from 'next/navigation';
const router = useRouter();
router.push('/dashboard', { scroll: false });
By using the router.push() method in combination with the scroll: false option, you can achieve the same effect as using the component.
Conclusion
In essence, whether you use the <Link>
component or the useRouter hook methods, you can easily disable scroll restoration in Next 13.
Thank you for reading.