Avoiding Page Jumps in Next.js 13+ When Changing Query Params

I recently encountered an issue that was driving me crazy in Next.js. Whenever I altered query parameters using the useRouter hook, the page would jump to the top. This was particularly jarring when I was updating the UI based on these query parameters.

What I initially thought was a quick page refresh turned out to be an unexpected scroll behavior. Fortunately, I found an easy fix.

When using useRouter().push() to change the URL and update query parameters, Next.js by default scrolls the page to the top.

This behavior can be disruptive, especially when trying to create a smooth user experience with modals or other dynamic content that doesn't require a full-page reload.

Here's an example of how I was initially changing the URL:

const router = useRouter();

// This would cause the page to jump to the top
router.push(`/${eventId}?dialog=register`);

The fix is surprisingly simple. Next.js's router.push() method accepts a second parameter, an options object. By adding { scroll: false } to this options object, we can prevent the automatic scroll behavior.

Here's the corrected version:

router.push(`/${eventId}?dialog=register`, { scroll: false });
``

This small adjustment — adding `{ scroll: false }` to your `router.push()` calls — can significantly improve the user experience in your Next.js applications. 

I've found it especially useful when you expect to update the UI with query parameters instead of the state.
Nextjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.