Client-Side Route Transitions with next/router
Illustrate how to implement smooth client-side transitions between routes using the useRouter hook and the next/router package.
import { useRouter } from 'next/router';
import { useEffect } from 'react';
function handleRouteChange(url, { shallow }) {
console.log(
`App is changing to ${url} ${
shallow ? 'with' : 'without'
} shallow routing`
);
}
function MyComponent() {
const router = useRouter();
useEffect(() => {
// Before the route changes, your code here can make transitions smooth
router.events.on('routeChangeStart', handleRouteChange);
// Cleanup the event handler on unmount
return () => {
router.events.off('routeChangeStart', handleRouteChange);
};
}, [router.events]);
// Trigger a route change programmatically
function goToAboutPage() {
router.push('/about');
}
return (
<div>
<button onClick={goToAboutPage}>Go to About Page</button>
</div>
);
}
export default MyComponent;
This code demonstrates how to listen for route changes in a Next.js application. We import the useRouter hook and useEffect to work with lifecycle events. The router.events.on method is used to attach a 'routeChangeStart' event. When a route change starts, handleRouteChange function will run, potentially allowing developers to implement custom transition logic. The router.push method is then used within the goToAboutPage function to navigate to the '/about' route when a button is clicked. We also ensure to clean up and remove the event listener when the component unmounts.