• Mail us
  • Book a Meeting
  • Call us
  • Chat with us

ReactJS

Shallow Routing in Next.js: A Quick Guide for Developers


Introduction

Shallow routing in Next.js is a key feature that enables you to update the URL of your application without triggering a full page reload or running getServerSideProps, getStaticProps or getInitialProps.

 

How Shallow Routing Works

By default, when you navigate to a new page in Next.js, the page's data fetching functions execute again. However, with shallow routing, you can update the URL while keeping the existing page state intact.

Example: Updating Query Parameters

Consider a scenario where you want to update a query parameter without reloading the page:

import { useRouter } from 'next/router';const ShallowRoutingExample = () => { const router = useRouter(); const updateQuery = () => { router.push( { pathname: '/products', query: { category: 'electronics' } }, undefined, { shallow: true } ); }; return ( <div> <h1>Shallow Routing Example</h1> <button onClick={updateQuery}>Update Query Without Reload</button> </div> );};export default ShallowRoutingExample;

 

Key Points:

  1. router.push with shallow: true → Updates the URL without fetching new data.
  2. No re-fetching of server-side props → The current state remains the same.
  3. Useful for UI state updates → Great for filters, pagination, or modal states.

 

When to Use Shallow Routing

  • Updating query parameters without fetching new data.
  • Changing UI state based on the URL (e.g., toggling a sidebar or modal).
  • Implementing client side filtering and sorting without making unnecessary API calls.
  •  

Conclusion

Shallow routing in Next.js helps in enhancing performance and improving user experience by allowing seamless URL updates without page reloads. It is particularly useful when working with dynamic UI changes that do not require new data fetching.

 

  Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise. 

0

Share

facebook
LinkedIn
Twitter
Mail
React

Related Center Of Excellence