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.
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:
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.